使用Unity IoC DI Container编写自定义DependencyResolver

时间:2016-01-30 10:16:39

标签: c# asp.net-mvc asp.net-mvc-4 dependency-injection unity-container

我有一个类A,它在构造函数中接受一个参数HttpSessionStateBase

在另一个类中,实现接口B的{​​{1}}将使用InterfaceB来构建自己。

如何编写代码以便在控制器中注入A

目前,这是执行DI寄存器的AddBinding方法:

B

1 个答案:

答案 0 :(得分:0)

如果A(Service1Impl),B(Service2Impl)并且在你的控制器和控制器中使用该容器进行控制反转注册,则B将被解析。

使用InjectionFactory

,您的统一注册可能如下所示
container.RegisterType<HttpSessionStateBase>(
new InjectionFactory(x => new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session)));
container.RegisterType<IService1, Service1Impl>();
container.RegisterType<IService2, Service2Impl>();

我已经使用类似这样的类/接口对此进行了测试:

public interface IService1 { }

public interface IService2 { }

public class Service1Impl : IService1 
{
    public Service1Impl(HttpSessionStateBase ctx)
    {

    }

}

public class Service2Impl : IService2
{
    public Service2Impl(IService1 service1)
    {

    }
}