0
我在我的業務層級別(簡化代碼)以下等級:團結子容器HierarchicalLifetimeManager MVC和Windows服務
public class StatusUpdater : IStatusUpdater
{
private readonly IStatusRepo _statusRepo;
public class StatusUpdater(IStatusRepo statusRepo)
{
_statusRepo = statusRepo;
}
public voic UpdateStatus(int id, string newStatus)
{
_statusRepo.UpdateStatus(id,newStatus);
}
}
所以目前在MVC方面我使用PerRequestLifetimeManager來控制壽命的DbContext。
但現在在窗口服務,我不能使用的,所以我要做到以下幾點,但它不正確的感覺,因爲它看起來很像服務定位:
using(var container = ConfiguredContainer.CreateChildContainer())
{
var statusUpdater = container.Resolve<IStatusUpdater>();
statusUpdater.UpdateStatus("test");
}
還有其他選擇嗎?並且在那裏使用在MVC應用中的相同的代碼和窗口服務,而不必2種類型的註冊的一種方法:
MVC:
container.RegisterType<IStatusRepo, StatusRepo>(new PerRequestLifetimeManager());
WindowsService:
container.RegisterType<IStatusRepo, StatusRepo>(new HierarchicalLifetimeManager());
不確定'Unity',但是在其他DI框架中,無論如何您都必須爲'MVC'和'Win Service'使用不同的註冊碼。直接調用「Resolve」方法總是會「聞到」,因爲這是DI框架的要求 - 在需要時解析實例。當我們在代碼中調用'.Resolve'方法時,意味着我們很可能做錯了什麼。我們可以在構造函數中注入實例,並改變使用它們的對象的生命範圍。 – Fabjan