依存性注入はかなり新しいので、これがアンチパターンかどうかを調べようとしています。
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からのものも必要です。これにより、ある種の循環依存関係が作成されます。
使用している依存性注入フレームワーク(この場合はNInject)をプロキシするインターフェイスをFoo.Sharedで定義しました。
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
、この場合のクラスの正確な依存関係が不明確になり、これは良い習慣ではないと思います。
他にどのようにこれを達成できますか?
何かご意見は?