的正确方法是什么

的正确方法是什么

我有以下项目布局:

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();的正确方法是什么?还是我这样做完全错误?

最佳答案

您可以通过注册自己的控制器工厂来使用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);
    }
}

关于c# - 从Controller实例化IRepository类的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2795527/

10-09 20:31