using a Handler in Web API and having Unity resolve per request

前端 未结 3 1161
一生所求
一生所求 2020-12-10 15:29

I am using Unity as my IoC framework and I am creating a type based on the value in the header of each request in a handler:

var container = new UnityContain         


        
3条回答
  •  醉酒成梦
    2020-12-10 15:32

    The problem you are having is caused by you mixing runtime values with design time dependencies. In general, the services you resolve from the container should not depend on runtime values in their constructor. You shouldn't do this, because components tend to live much longer than runtime values and injecting runtime values into components, makes it much harder to diagnose and verify the container's configuration.

    Instead, hide that value behind a service that can provide consumers with that instance when required. For instance:

    public interface IHeaderValueProvider
    {
        HeaderValue GetCurrentValue();
    }
    

    You can create an implementation that can be easily registered and injected into any component that needs that value. Anytime after the construction phase, those components can call the GetCurrentValue() method on the injected IHeaderValueProvider dependency.

提交回复
热议问题