Rem*_*tec 3 c# inversion-of-control unity-container
有没有办法使用Unity框架将整数作为参数传递给构造函数或已解析的对象?
伪码..
IService svc = Container.Resolve<ConcreteService>()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,混凝土服务将是这样的......
public class ConcreteService
{
public ConcreteService(int val)
{
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我需要在xml配置中执行此操作,而不是在代码中执行此操作.
提前致谢.
希望我理解你
public class ConcreteService {
public int Val { get; set; }
public ConcreteService(int val) {
Val = val;
}
}
Run Code Online (Sandbox Code Playgroud)
现在让我们配置统一.
var container = new UnityContainer();
container.RegisterType<ConcreteService>();
container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>(new InjectionConstructor(1));
container.RegisterType<ConcreteService>("for42");
container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>("for42",
new InjectionConstructor(42));
container.RegisterType<ConcreteService>("for31");
container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>("for31",
new InjectionConstructor(31));
Debug.WriteLine(container.Resolve<ConcreteService>().Val); //1
Debug.WriteLine(container.Resolve<ConcreteService>("for42").Val); //42
Debug.WriteLine(container.Resolve<ConcreteService>("for31").Val); //31
Run Code Online (Sandbox Code Playgroud)
"for42"的等效配置是
<type type="ConcreteService" name="for42">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
Microsoft.Practices.Unity.Configuration">
<constructor>
<param name="val" parameterType="int">
<value value="42"/>
</param>
</constructor>
</typeConfig>
</type>
Run Code Online (Sandbox Code Playgroud)
它完全相同但没有冗余的typeConfig节点
<type type="ConcreteService" name="for42">
<constructor>
<param name="val" parameterType="int">
<value value="42"/>
</param>
</constructor>
</type>
Run Code Online (Sandbox Code Playgroud)