想象一下,我将通过工厂创建一些东西:
public sealed class MyClass
: IMyClass
{
private IMyDao MyDao { get; set; }
public MyClass(IMyDaoFactory factory)
{
MyDao = factory.MyDao;
}
}
这可以通过服务解决:
public sealed class MyService
: IMyService
{
private readonly IMyClass myClass;
public MyService(IMyDaoFactory factory)
{
myClass = new MyClass(factory);
}
}
在Unity中很容易接线:
var container = new UnityContainer();
container.RegisterType<IMyService, MyService>();
container.RegisterType<IMyDaoFactory, MyDaoFactory>();
container.RegisterType<IMyClass, MyClass>();
注意到MyClass的注册,如何设置Unity以便它自动注册并通过工厂解决?即然后我不再需要:
myClass = new MyClass(factory);
仅
this.myClass = myClass; (passed through the constructor
as IMyClass and resolved by Unity)
希望这是有道理的。提前谢谢。
答案 0 :(得分:0)
尝试将MyService
的构造函数切换为需要IMyClass
的单个实例; Unity应该自动填补那里的空白,并根据类型签名进行实例化。
public MyService(IMyClass _myClass)
{
myClass = _myClass;
}
虽然我也会改名,但是呃。