0

DbContextユニティ子コンテナHierarchicalLifetimeManager MVCとWindowsサービス

しかし、今、私はそれを使用することはできませんWindowsサービスでは、私は次の操作を実行するつもりだったが、それはのServiceLocatorのようにたくさん見えるので、それが正しい感じていない:

using(var container = ConfiguredContainer.CreateChildContainer()) 
{ 
    var statusUpdater = container.Resolve<IStatusUpdater>(); 
    statusUpdater.UpdateStatus("test"); 
} 

他のオプションはありますか?そして、登録の2種類がなくても、MVCアプリとWindowsのサービスで同じコードを使用する方法があります:

MVC:

container.RegisterType<IStatusRepo, StatusRepo>(new PerRequestLifetimeManager()); 

Windowsサービス:

container.RegisterType<IStatusRepo, StatusRepo>(new HierarchicalLifetimeManager()); 
+0

「Unity」についてはわかりませんが、他のDIフレームワークでは、とにかく「MVC」と「Winサービス」に異なる登録コードを使用する必要があります。 'Resolve'メソッドへの直接呼び出しは、DIフレームワークが何のために作られているかのように常に「臭い」 - それが必要なときにインスタンスを解決するためです。私たちのコードで '.Resolve'メソッドを呼び出すと、何か間違っている可能性が最も高いことを意味します。コンストラクタにインスタンスを挿入し、それを使用するオブジェクトのライフスコープを変更することができます。 – Fabjan

答えて

0

私は通常登録あなた自身のアセンブリの私の型は、おそらくあなたのようでしたが、実行中のアセンブリに固有のものがあるときは、その実行アセンブリの登録でオーバーライドします。

// In BusinessProcessor 
container.RegisterType<IBusinessProcessorA, MyBusinessProcessorA1>(); 
container.RegisterType<IBusinessProcessorA, MyBusinessProcessorA2>(); 
container.RegisterType<IBusinessProcessorB, MyBusinessProcessorB1>(); 

// In DataAccessLayer 
container.RegisterType<IRepository, Repository<A>>("A", new HierarchicalLifetimeManager()); 
container.RegisterType<IRepository, Repository<B>>("B", new HierarchicalLifetimeManager()); 
container.RegisterType<IRepository, Repository<C>>("C", new HierarchicalLifetimeManager()); 

// In WindowsService 
Register(BusinessProcessor); // Call to have the BusinessProcessor register it's own things. 
Register(DataAccessLayer);  // Call to have the DataAccessLayer register it's own things. 
container.RegisterType<IService, MyService>(); 

// In WebApplication 
Register(BusinessProcessor); // Call to have the BusinessProcessor register it's own things. 
Register(DataAccessLayer);  // Call to have the DataAccessLayer register it's own things. 
container.RegisterType<IController, MyController>(); 
container.RegisterType<IRepository, Repository<A>>("A", new PerRequestLifetimeManager()); 

異なる名前の登録と、DALに、リポジトリを登録し、BusinessProcessorsのためにそう、それは私がお勧めしませんという事実を意識あなたの全体のソリューションを意味しますすることができ別の方法。まったく。

関連する問題