Castle Windsor - 注册和解决相同接口的缓存和非缓存实现

时间:2012-04-04 14:59:37

标签: asp.net-mvc dependency-injection castle-windsor

我有一个服务接口ICustomerService,它有两种类型实现:

public class CustomerService : ICustomerService
{
    // stuff
}

public class CachedCustomerService : ICustomerService
{
    public CachedCustomerService(CustomerService service) { }
}

缓存服务然后只缓存并委托给普通服务。

对于注册,我将ICustomerService解析为CachedCustomerService,然后CustomerService刚刚注册为自己的类型。

这很好用。

我想知道的是,我是否可以让CachedCustomerService需要一个接口而不是具体的CustomerService。原因是我们最终可能会使用两种类型的CustomerService,并且我希望避免(如果可能的话)特定于每个类型的缓存版本。

因此CachedCustomerService的构造函数将更改为:

public class CachedCustomerService : ICustomerService
{
    // notice the ICustomerService
    public CachedCustomerService(ICustomerService service) { }
}

我完全控制了注册,但解决方案是由asp.net mvc的碗完成的。

谢谢!

1 个答案:

答案 0 :(得分:3)

所有与温莎城堡有关的事情就像this article所暗示的那样。 因此,在您的情况下,您只需要首先使用缓存服务注册客户服务:

var container = new WindsorContainer()
.Register(
Component.For(typeof(ICustomerService)).ImplementedBy(typeof(CachedCustomerService)),
Component.For(typeof(ICustomerService)).ImplementedBy(typeof(CustomerService))
);

然后,缓存客户服务可以使用ICustomerService作为内部/包装对象,如下所示:

public class CachedCustomerService : ICustomerService
{
    private ICustomerService _customerService;
    public CachedCustomerService(ICustomerService service)
    {
        Console.WriteLine("Cached Customer service created");
        this._customerService = service;
    }

    public void Run()
    {
        Console.WriteLine("Cached Customer service running");
        this._customerService.Run();
    }
}

然后分辨率正常:

ICustomerService service = container.Resolve<ICustomerService>();
service.Run();