开发者

Use interface between model and view in ASP.NET MVC

开发者 https://www.devze.com 2022-12-31 04:02 出处:网络
I am using asp.net MVC 2 to develop a site. IUser is used to be the interface between model and view for better separation of concern. However, things turn to a little messy here. In the controller th

I am using asp.net MVC 2 to develop a site. IUser is used to be the interface between model and view for better separation of concern. However, things turn to a little messy here. In the controller that handles user sign on: I have the following:

        IUserBll userBll = new UserBll();
        IUser newUser = new User();

        newUser.Username = answers[0].ToString();
        newUser.Email = answers[1].ToSt开发者_如何学编程ring();

        userBll.AddUser(newUser);

The User class is defined in web project as a concrete class implementing IUser. There is a similar class in DAL implementing the same interface and used to persist data. However, when the userBll.AddUser is called, the newUser of type User can't be casted to the DAL User class even though both Users class implementing the interface (InvalidCastException).

Using conversion operators maybe an option, but it will make the dependency between DAL and web which is against the initial goal of using interface.

Any suggestions?


You should have a project which handles dependency injection. This project references your Domain project (where IUserBll is defined), and the project which has the DLL implementation. So your MVC project will reference the dependency injection project and given a particular interface, ask the DI for an implementation of it.

Have a look at StructureMap or Castle Windsor.

    //Global.asax
    protected void Application_Start()
    {
        ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
    }

    //Dependency Injection Project:
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(Type controllerType)
        {
            if (controllerType != null)
            {
                return (IController)ObjectFactory.GetInstance(controllerType);
            }
            return null;
    }
}

That way your controller can look more like:

public class SomeController
{
  private IUserBll _repository;
  public SomeController(IUserBll repository)
  {
    _repository = repository;
  }

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Index(Someform f)
  {
      ...
      _repository.AddUser(...);
  }
}

When you use a StructureMap controller factory for example, MVC will get the dependencies into your controller behind the scenes.

0

精彩评论

暂无评论...
验证码 换一张
取 消