C# WinRT Caliburn Micro SimpleContainer:在容器中注册装饰器
如何在WinRT universal app中使用caliburn micro为以下场景注册装饰器: 我有Caliburn micro容器,它是寄存器类型:C# WinRT Caliburn Micro SimpleContainer:在容器中注册装饰器,c#,wpf,windows-runtime,ioc-container,caliburn.micro,C#,Wpf,Windows Runtime,Ioc Container,Caliburn.micro,如何在WinRT universal app中使用caliburn micro为以下场景注册装饰器: 我有Caliburn micro容器,它是寄存器类型: _container.RegisterInstance(IService, "", Service); 我创建了以下iSeries设备实现和装饰器: public interface IService { void Do(); } public class Service : IService { public void
_container.RegisterInstance(IService, "", Service);
我创建了以下iSeries设备实现和装饰器:
public interface IService
{
void Do();
}
public class Service : IService
{
public void Do() { }
}
public class LoggedService<T> : IService
where T : IService
{
private T decoratee;
private ILogger logger;
public LoggedService(ILogger logger, T decoratee)
{
this.decoratee = decoratee;
this.logger = logger;
}
public void Do()
{
logger.Debug("Do()");
decoratee.Do();
}
}
public class ProfiledService<T> : IService
where T : IService
{
private T decoratee;
private IProfiler profiler;
public ProfiledService(IProfiler profiler, T decoratee)
{
this.decoratee = decoratee;
this.profiler = profiler;
}
public void Do()
{
profiler.Start();
decoratee.Do();
profiler.Stop();
}
}
如何注册LoggedService和ProfileService这样的装饰程序,并根据有条件地需要哪一个来解决这些问题?SimpleContainer在这里名副其实,它不支持上下文注册之类的功能。您可以使用命名注册和AddHandler等功能来创建自定义逻辑
这样做的方法是为服务添加一个命名注册,然后为IService添加一个AddHandler,它使用容器为实际命名注册实例化decorator。如果你有两个级别的装饰师,那就有点傻了
如果你真的想使用decorator,或者有很多decorator,我建议你使用一个更高级的容器,在decorator周围有特定的功能。你可以这样做,但是它可能不是最佳的。我设计了这些扩展方法来解决这个问题 我们的想法是创建一个子容器,将decorator实现注册为自己的服务,然后注销原始处理程序,并注册一个新的处理程序,该处理程序使用子容器查找decorator 缺点是我们为注册的每个decorator创建一个新的子容器,但是开销应该可以忽略不计 公共静态SimpleContainer RegisterDecorator此SimpleContainer容器,类型服务,类型装饰器 { if!container.HasHandlerservice,null { 抛出新ArgumentExceptionnameofservice; } var childContainer=container.CreateChildContainer; childContainer.RegisterSingletondecorator,null,decorator; container.UnregisterHandlerservice,空; container.RegisterHandlerservice,null,c=>childContainer.GetInstancedecorator,null; 返回容器; } 公共静态SimpleContainer装饰此SimpleContainer容器 { container.registerDecoratorTypeOfService、TypeOfDecorator; 返回容器; } 用法: 接口IFoo{} A类:IFoo{} B类:IFoo { 公共BIFoo x{} } C类:IFoo { 公共CIFoo x{} } var容器=新的SimpleContainer; 集装箱。单件; 容器。装饰; 容器。装饰; var foo=container.GetInstance; Truefoo是C;
在某个地方,您将指定如何构造任何需要IService的东西。在这里,您可以使用命名注册或类似的方法来区分TypeShow。尽管如此,我确实认为您的问题证明了IoC容器的局限性。当你开始命名你正在将业务逻辑嵌入到容器设置中的东西时,你能给我一个如何实现这一点的例子吗?嗯,我没有使用Caliburn.micro。看起来你可以用键注册类型?Unity允许为这类事情命名实例。这里我也可以使用名称注册,但这对我有什么帮助?还有一个名称中包含Simple的容器,它可能不符合它的名称,尽管它确实有Through,这是