Microsoft Unity the difference between interface i

2019-07-13 16:48发布

问题:

What's the difference between interface interception and constructor Injection in asp.net unity? I am lack of understanding DI with Unity I am working on an old project and in unity.config, some like this,

<register type="ICRIC2012TrialUserService" mapTo="CRIC2012TrialUserService">
        <lifetime type="perthread"/>
        <interceptor type="InterfaceInterceptor"/>
        <policyInjection/>
</register>

but some do not have

<interceptor type="InterfaceInterceptor"/>

but in project these class and interface work in same way, like this

private readonly IIncomingEstimateService _incomingEstimateService;

        public ContractService(IIncomingEstimateService incomingEstimateService)
        {
            _incomingEstimateService = incomingEstimateService;
        }

回答1:

Interception and injection are two different things.

Interception is usually used to add cross-cutting concerns (like logging) to classes without having to implement them over and over again. Interception in Unity works by generating proxies that receive incoming method calls and channel them through a pipeline of so called interceptors until the call finally reaches the original target object.

These two articles introduce how interception with Unity works.

Interceptors in Unity

Using Interception with Unity

Constructor injection is one way to implement the Dependency Injection Pattern. It is a pattern that tells you how to structure your application to decouple components.

There are a lot of articles on the web.

Inversion of Control Containers and the Dependency Injection pattern

The Dependency Injection Pattern – What is it and why do I care?

Interception and injection are something completely different. But some Dependency Injection containers (like Unity) allow you to do both. You can inject dependencies into classes and intercept calls to those classes using the container infrastructure.