如何从控制器获取unity config中定义的统一容器?

时间:2017-02-27 10:40:21

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

我正在尝试在Mvc应用程序中配置Microsoft unity

我在unity.config中定义了单位配置:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer(); 
        container.RegisterType<IAccessLogBLL, AccessLogBLL>();            
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}

我从global.asax调用该配置:

 protected void Application_Start()
    {
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        UnityConfig.RegisterComponents();


    }

现在我在调用resolve方法之前从控制器定义了该容器的配置,并且工作正常,但是如何使用unity.config中定义的容器? 是否有任何“getContainer”方法或我必须为Unity容器声明全局变量?

   private IAccessLogBLL _accessLogBLL;
   public AccessLogController()
    {

        IUnityContainer container = new UnityContainer();            
        container.RegisterType<IAccessLogBLL, AccessLogBLL>();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        _accessLogBLL = container.Resolve<IAccessLogBLL>(new ParameterOverride("unitOfWork", UnitOfWork));
    }

感谢和抱歉我的英语

1 个答案:

答案 0 :(得分:1)

我告诉容器变量静态,它工作正常。但我现在不认为这是最好的解决方案。

public static class UnityConfig
{
    public static IUnityContainer container;
    public static void RegisterComponents()
    {
        container = new UnityContainer(); 
        container.RegisterType<IAccessLogBLL, AccessLogBLL>();            
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}

并形成我的控制器构造函数:

public AccessLogController()
    {

        _accessLogBLL = UnityConfig.container.Resolve<IAccessLogBLL>(new ParameterOverride("unitOfWork", UnitOfWork));

    }