对于依赖注入来说很新颖,我试图弄清楚这是否是反模式。使用依赖注入来注入依赖注入器
比方说,我有3个组件:
Foo.Shared - this has all the interfaces
Foo.Users - references Foo.Shared
Foo.Payment - references Foo.Shared
Foo.Users需要是内Foo.Payment建立了一个对象,并Foo.Payment还需要从Foo.Users东西。这会产生某种循环依赖。
我已经在Foo.Shared中定义了一个代理我使用的依赖注入框架(在这种情况下为NInject)的接口。
public interface IDependencyResolver
{
T Get<T>();
}
在容器应用程序,我有这个接口的实现:
public class DependencyResolver:IDependencyResolver
{
private readonly IKernel _kernel;
public DependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public T Get<T>()
{
return _kernel.Get<T>();
}
}
的配置是这样的:
public class MyModule:StandardModule
{
public override void Load()
{
Bind<IDependencyResolver>().To<DependencyResolver>().WithArgument("kernel", Kernel);
Bind<Foo.Shared.ISomeType>().To<Foo.Payment.SomeType>(); // <- binding to different assembly
...
}
}
这让我来实例化的Foo.Payment.SomeType
一个新对象来自Foo.Users内部,无需直接参考:
public class UserAccounts:IUserAccounts
{
private ISomeType _someType;
public UserAccounts(IDependencyResolver dependencyResolver)
{
_someType = dependencyResolver.Get<ISomeType>(); // <- this essentially creates a new instance of Foo.Payment.SomeType
}
}
这使得它不清楚UserAccounts
类的确切依赖关系在这种情况下,这让我觉得这不是一个好习惯。
我该怎么做到这一点?
有什么想法?
+1只是绕口令称号。 – womp 2009-12-12 01:01:41
同样在这里,我爱的标题:) – 2009-12-12 01:06:52