1

我有一个 MVC 应用程序,我在其中实现 CQRS,在其中我将保存数据与将数据读取到单独的接口中分开。我正在使用构造函数注入将这些接口的具体实例注入控制器。对于构造函数注入,我使用 Unity 容器。见下面的例子

//The Employee controller 
public class EmployeeController : Controller
{
    IEmployeeRepository _Writer;

    IEmployeeQuery _Reader;

    //constructor injection
    public EmployeeController(IEmployeeRepository writer, IEmployeeQuery reader)
    {
        this._Writer = writer;
   this._Reader = reader;   

    }


    //To Do: constructor injection for write operations only
    public EmployeeController(IEmployeeRepository writer)
    {
        this._Writer = writer;

    }

    //To Do: constructor injection for read operations only
    public EmployeeController(IEmployeeQuery reader)
    {
        this._Reader = reader;

    }
}


//Registration of the concrete types in the unity container.
public static class Bootstrapper
{
    public static void ConfigureUnityContainer()
    {
        IUnityContainer container = new UnityContainer();

        container.RegisterType<IEmployeeRepository, EmployeeRepository>(new HttpContextLifetimeManager<IEmployeeRepository>());
        container.RegisterType<IEmployeeQuery, EmployeeQueries>(new HttpContextLifetimeManager<IEmployeeQuery>());
        ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
    }
}

//The derived Controller Factory for injection dependencies in the Controller constructor
public class UnityControllerFactory : DefaultControllerFactory
{
    IUnityContainer container;

    public UnityControllerFactory(IUnityContainer container)
    {
        this.container = container;
    }
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {


        try
        {
            if (controllerType == null)
            {
                throw new ArgumentNullException("controllerType");
            }

            if (!typeof(IController).IsAssignableFrom(controllerType))
            {
                throw new ArgumentException(String.Format("Type requested is not a controller: {0}", controllerType.Name), "controllerType");
            }

            return container.Resolve(controllerType) as IController;





        }
        catch (Exception)
        {

            return null;
        }
    }
}

我发现对于任何操作,我要么获取数据,要么写入数据,但不能两者兼而有之。在这种情况下,我需要根据需要初始化的“_Writer”或“_Reader”有条件地调用控制器构造函数。

如何才能做到这一点 ?

4

2 回答 2

1

延迟加载组件呢?您解决了两个依赖项,但只有一个真正使用的依赖项被初始化。

示例:http: //pwlodek.blogspot.com/2010/05/lazy-and-ienumerable-support-comes-to.html

于 2012-07-25T10:29:19.570 回答
1

看起来你有一个控制器,你应该使用两个?如果您永远不需要能够读写,我会考虑将该组件重构为单一职责。

如果您不想这样做,我会考虑注入 NullObject 而不是根本不注入该依赖项。看到这个线程

TecX项目包含一个模仿 NInject 的上下文绑定的扩展。这将允许您指定何时注入什么依赖项。该代码可以在TecX.Unity项目(文件夹ContextualBinding)中找到。展示如何使用它的测试在TecX.Unity.ContextualBinding.Test项目中)。

于 2012-07-16T11:54:05.793 回答