2010-10-23 39 views
28

如何注册类型没有NO PARAMETER构造函数的容器。如何使用PARAMETER构造函数注册类型?

事实上,我的构造函数接受一个字符串,而且我通常传递一个表示Path的字符串。

所以当我解决它会自动创建新的类型,但传入一个字符串?

回答

52

很简单。当你注册构造函数时,你只需传递你想为参数注入的值。容器根据值的类型(API)或参数名称(XML)匹配您的构造函数。

在API中,你会怎么做:

container.RegisterType<MyType>(new InjectionConstructor("My string here")); 

这将选择一个构造函数一个字符串,并决心时间将通过字符串“我在这里的字符串”。

等价的XML(使用2.0配置模式)将是:

<register type="MyType"> 
    <constructor> 
    <param name="whateverParameterNameIs" value="My string here" /> 
    </constructor> 
</register> 
+0

谢谢,正是我需要的。 – Martin 2010-10-24 15:36:25

14

您还可以使用内置的InjectionConstructor和ResolvedParameter其中的connectionString是要使用的数据库连接字符串。

// install a named string that holds the connection string to use 
container.RegisterInstance<string>("MyConnectionString", connectionString, new ContainerControlledLifetimeManager()); 

// register the class that will use the connection string 
container.RegisterType<MyNamespace.MyObjectContext, MyNamespace.MyObjectContext>(new InjectionConstructor(new ResolvedParameter<string>("MyConnectionString"))); 

var context = container.Resolve<MyNamespace.MyObjectContext>(); 

你可以把它连一步,有MyObjectContext的多个命名实例,每个实例使用自己的连接字符串到不同的数据库。

相关问题