![](/img/trans.png)
[英]How should I register this type that has parameterized constructor, in Unity?
[英]how to register parameterized based constructor classes in unity container in C#?
我是依赖注入模式的新手。 请查看以下情况。 现在,我下面的代码紧密结合在一起。 我想使它成为轻微耦合。
有人可以帮我使用Unity实施依赖注入吗?
// Implementation of class A
public class A
{
public B b{get;set;}
public A(B b,string c)
{
this.b=b;
this.A(b,c);
}
}
//Implementation of Class B
public class B
{
public int value1 {get;private set;}
public string stringValue {get;private set;}
public B(int value,string strValue)
{
this.value1=value;
this.stringValue=strValue;
}
}
//Implementation of class C
public class C
{
public void Dosomething()
{
B b=null;
string value="Something";
// Here I need to implement unity to resolve tight coupling
// without creating object of Class A
A a=new A(b,value);
}
}
我基于打击可能重复的问题而感到厌倦。 但是我仍然面临着同样的问题。
如何在Unity中注册具有参数化构造函数的类型?
代替此行,我实现了以下代码
A a=new A(b,value);
var container=new UnityContainer();
container.RegisterType<A>();
container.RegisterType<B>();
A a=new A(b,container.ResolveType<B>();
但这没有帮助我。
首先,我会建议您通过引入接口进一步分离类,以便可以按以下方式实现类C:
public class C
{
private readonly IA a;
private readonly IB b;
public C(IA a, IB b)
{
this.a = a;
this.b = b;
}
public void Dosomething()
{
// do something with this.a or this.b.
}
}
然后,您可以注册并解析您的课程,如下所示:
var container = new UnityContainer();
container.RegisterType<IB, B>(new InjectionConstructor(1, "Test"));
container.RegisterType<IA, A>(new InjectionConstructor(new ResolvedParameter<IB>(),"Test"));
container.RegisterType<IC, C>();
var c = container.Resolve<IC>();
尽管我建议使用上述方法,但也可以选择在解决时指定进样值,例如:
container.RegisterType<IB, B>();
container.Resolve<IB>(
new ParameterOverride("value", 1),
new ParameterOverride("strValue", "Test"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.