从Controller实例化IRepository类的正确方法是什么?

时间:2010-05-08 20:32:46

标签: c# model-view-controller dependency-injection irepository

我有以下项目布局:

MVC UI
|...CustomerController (ICustomerRepository - how do I instantiate this?)

Data Model
|...ICustomerRepository

DAL (Separate Data access layer, references Data Model to get the IxRepositories)
|...CustomerRepository (inherits ICustomerRepository)

当Controller无法看到DAL项目时,说ICustomerRepository repository = new CustomerRepository();的正确方法是什么?或者我完全错了吗?

1 个答案:

答案 0 :(得分:2)

您可以使用IoC容器通过注册您自己的控制器工厂来解析映射,该工厂允许容器解析控制器 - 容器将解析控制器类型并注入接口的具体实例。

使用 Castle Windsor

的示例

MvcApplication类的global.asax中

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
}

WindsorControllerFactory上课

using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

public class WindsorControllerFactory : DefaultControllerFactory
{
    WindsorContainer container;

    public WindsorControllerFactory()
    {
        container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));

        var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                              where typeof(IController).IsAssignableFrom(t)
                              select t;

        foreach (Type t in controllerTypes)
            container.AddComponentWithLifestyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        // see http://stackoverflow.com/questions/1357485/asp-net-mvc2-preview-1-are-there-any-breaking-changes/1601706#1601706
        if (controllerType == null) { return null; }

        return (IController)container.Resolve(controllerType);
    }
}