开发者

IWindsorInstaller in an assembly and resolving local dependencies

I have a WPF MVVM application that has a model and services assembly. I'm trying to figure out how to us开发者_开发百科e the Windsor container to resolve local (services in the service layer) dependencies, but the only thing I can figure out feels kludgy and incorrect.

Services installer:

public class ServicesInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        //Services
        container.Register(
            Component.For<IServiceA>().ImplementedBy<ServiceA>().LifeStyle.Singleton,
            Component.For<IServiceB>().ImplementedBy<ServiceB>().LifeStyle.Singleton
    }
}

Service consumer (located in services):

public class ServiceConsumer
{
     public SomeMethodThatUsesServiceAOnlyOcassionally()
     {
         //buncha logic.
         if (allThatFailed)
         {
                 ??? ResolveServiceA ???
         }
     }
} 

Because I'm not dependent on ServiceA that often, I don't want to pass it in via constructor injection or property injection. I'd add a static container instance to the Installer, but I have to believe that there's a more idiomatic solution than that.


For what you want are common DI patterns.

If your service has an optional dependency (in other words, it can do its thing with the absence of the dependency), you should use property injection. If your service needs that dependency to properly work, you should use constructor injection (because it is a required dependency). If however, the creation of that service is time consuming, you should hide that dependency behind a proxy, that can create that dependency lazily when the proxy is called for the first time.

In your case however, ServiceA is registered as a singleton, so it is only created once during the lifetime of the application. In other words, there is no reason to use a proxy and since your service can't live without it, you should just use constructor injection, because that clearly communicates that IServiceA is a required dependency.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜