Microsoft Unity,构造函数中的参数

时间:2010-04-08 12:34:57

标签: unity-container enterprise-library

我正在使用Unity与MVC和NHibernate。不幸的是,我们的UnitOfWork驻留在一个不同的.dll中,它没有默认的空.ctor。 这就是我注册NHibernate的方法:

var connectionString = ConfigurationManager.ConnectionStrings
    ["jobManagerConnection"].ConnectionString;
var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"];
container.RegisterType<IUnitOfWork, UnitOfWork>(
    new ContainerControlledLifetimeManager());

在我的WebController中我有这个:

/// <summary>Gets or sets UnitOfWork.</summary>
[Dependency]
public IUnitOfWork UnitOfWork { get; set; }

问题是UnitOfWork的构造函数需要2个必需字符串。我如何设置此接口的RegisterType以传递从web.config中检索到的两个参数? 有可能吗?

2 个答案:

答案 0 :(得分:4)

这样的事情应该这样做:

var connectionString = ConfigurationManager.ConnectionStrings
    ["jobManagerConnection"].ConnectionString;
var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"];

container.RegisterType<IUnitOfWork, UnitOfWork>(
    new InjectionConstructor(connectionString, assemblyMap),
    new ContainerControlledLifetimeManager());

答案 1 :(得分:1)

比我想象的更容易:

        var connectionString = ConfigurationManager.ConnectionStrings["jobManagerConnection"].ConnectionString;
        var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"];
        container
            .RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager())
            .Configure<InjectedMembers>()
            .ConfigureInjectionFor<UnitOfWork>(new InjectionConstructor(connectionString, assemblyMap));