Dependency Injection composition root and decorator pattern

前端 未结 3 887
后悔当初
后悔当初 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:13

    Preamble

    Whenever you are having trouble with a DI Container (Unity or otherwise), ask yourself this: is using a DI Container worth the effort?

    In most cases, the answer ought to be no. Use Pure DI instead. All your answers are trivial to answer with Pure DI.

    Unity

    If you must use Unity, perhaps the following will be of help. I haven't used Unity since 2011, so things may have changed since then, but looking up the issue in section 14.3.3 in my book, something like this might do the trick:

    container.RegisterType("custSvc");
    container.RegisterType(
        new InjectionConstructor(
            new ResolvedParameter("custSvc")));
    

    Alternatively, you may also be able to do this:

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

    This alternative is easier to maintain because it does not rely on named services, but has the (potential) disadvantage that you can't resolve CustomerService through the ICustomerService interface. You probably shouldn't be doing that anyway, so it ought not to be an issue, so this is probably a better alternative.

提交回复
热议问题