對於依賴注入來說很新穎,我試圖弄清楚這是否是反模式。使用依賴注入來注入依賴注入器
比方說,我有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