Dependency Injection composition root and decorator pattern

前端 未结 3 895
后悔当初
后悔当初 2021-02-12 13:26

I\'m getting StackoverflowException\'s in my implementation of the decorator pattern when using dependency injection. I think it is because I\'m \"missing\" somethi

3条回答
  •  忘了有多久
    2021-02-12 14:09

    Building upon Mark's second answer I'd look to registering the CustomerService with a InjectionFactory and only register it with the service type without it's interface like:

    containter.RegisterType(new InjectionFactory(
        container => new CustomerService(containter.Resolve>())));
    

    This would then allow, as in Mark's answer, for you to register the logging object like:

    containter.RegisterType(new InjectionConstructor(
        new ResolvedParameter()));
    

    This is basically the same technique that I use whenever I require something to be lazily loaded as I don't want my objects to depend upon Lazy and by wrapping them in proxy allows me to only inject IService but have it resolved lazily through the proxy.

    This will also allow you to pick and choose where either the logging object or the normal object is injected instead of requiring magic strings by simply resolving a CustomerService for your object instead of the ICustomerService.

    For a logging CustomerService:

    container.Resolve()

    Or for a non-logging CustomerService:

    container.Resolve()

提交回复
热议问题