WCF and Unity - Dependency Injection

I am trying to connect WCF to dependency injection. All the examples I found are based on the assumption that you are either using the .svc service (ServiceHostFactory) or using app.config to configure the container. Other examples are also based on the fact that the container is passed to classes.

I need a solution where the container is not being passed (not closely related to Unity). Where I do not use the configuration file to configure the container and where I use self-service.

The problem is that, as I see it, ServiceHost uses the service implementation type as a parameter, and what does it do to use InstanceProvider?

The solution I have come to at the moment is to register the ServiceHost (or specialization) in a type register with a name (for example, container.RegisterInstance<Type>("ServiceName", typeof(Service); ).

And then container.RegisterType<UnityServiceHost>(new InjectionConstructor(new ResolvedParameter<Type>("ServiceName"))); to register a ServiceHost.

Are there any better solutions? I, probably, in my assumptions.

Best wishes,
Michael

+4
source share
1 answer

Use Constructor Injection to connect to your service like any other class.

Here you can write about how to make WCF understandable for the constructor injector .

The example in this answer demonstrates Poor Man Injection , but you can extrapolate it and configure the UnityContainer instance in ServiceHostFactory instead of a hard-coded dependency.

You pass the container instance up to the custom IInstanceProvider. Now you can use the container in the GetInstance method:

 public object GetInstance(InstanceContext instanceContext) { var serviceType = instanceContext.Host.Description.ServiceType; return this.container.Resolve(serviceType); } 
+3
source

Source: https://habr.com/ru/post/1304856/


All Articles