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()); 
+0

不确定'Unity',但是在其他DI框架中,无论如何您都必须为'MVC'和'Win Service'使用不同的注册码。直接调用“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这样做,但是这将意味着你的整体解决方案知道这一事实,我不会推荐。完全一样。