团结和委托 [英] Unity and delegate
问题描述
我使用的是统一的依赖注入框架。
我有两个班,每个参加的构造相同的委托参数。解决时,每个班应该得到一个不同的方法。
我可以设置此不使用属性?如果不是你会怎么用的属性呢?
I'm using the Unity dependency injection framework. I have two classes, that each take the same delegate parameter in the constructor. Each class should get a different method when resolved. Can I set this up without using attributes ? If not how would you do it with attributes?
推荐答案
是的,你可以装饰用[依赖]属性属性或者构造函数的参数
Yep, you can decorate properties or constructor parameters with the [Dependency] attribute.
这例子是不使用的代表,它只是使用一个接口代替,但它显示了两个相同的接口被用不同的名字登记的,而一个类请求尤其之一,它的构造:
This example isn't using delegates, it's just using an interface instead, but it shows two of the same interface being registered with different names, and a class requesting a particular one in its constructor:
[TestClass]
public class NamedCI
{
internal interface ITestInterface
{
int GetValue();
}
internal class TestClassOne : ITestInterface
{
public int GetValue()
{
return 1;
}
}
internal class TestClassTwo : ITestInterface
{
public int GetValue()
{
return 2;
}
}
internal class ClassToResolve
{
public int Value { get; private set; }
public ClassToResolve([Dependency("ClassTwo")]ITestInterface testClass)
{
Value = testClass.GetValue();
}
}
[TestMethod]
public void Resolve_NamedCtorDependencyRegisteredLast_InjectsCorrectInstance()
{
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ITestInterface, TestClassOne>("ClassOne");
container.RegisterType<ITestInterface, TestClassTwo>("ClassTwo");
container.RegisterType<ClassToResolve>();
var resolvedClass = container.Resolve<ClassToResolve>();
Assert.AreEqual<int>(2, resolvedClass.Value);
}
}
[TestMethod]
public void Resolve_NamedCtorDependencyRegisteredFirst_InjectsCorrectInstance()
{
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ITestInterface, TestClassTwo>("ClassTwo");
container.RegisterType<ITestInterface, TestClassOne>("ClassOne");
container.RegisterType<ClassToResolve>();
var resolvedClass = container.Resolve<ClassToResolve>();
Assert.AreEqual<int>(2, resolvedClass.Value);
}
}
}
这篇关于团结和委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!