keithwill
keithwill

Reputation: 2044

Ninject WCF: Attribute Injection

I am using the Ninject WCF extension project to do dependency injection on my web service. If I add an attribute to my web service (such as a an IServiceBehavior), how can I inject dependencies into that attribute when it is created at runtime?

Upvotes: 1

Views: 747

Answers (2)

Shibbz
Shibbz

Reputation: 249

I disagree that attributes should not have dependencies in them. Often times validation attributes will have unavoidable dependencies. Attributes are an excellent example of DRY when used correctly.

The approach @wllmsaccnt took is essentially the KernelContainer approach which was removed in 2.2 - but worse. Now the attribute is coupled to the WCF app.

IMO this is precisely the reason I disagree with the removal of the KernelContainer. I'd definitely prefer injection over service locator, but I really don't see why service locator is discouraged when you are working within systems that you can't change or control.

It's surely better than writing additional custom code - for every application - that is most likely less maintainable and less testable than ServiceLocator.

Upvotes: 1

Remo Gloor
Remo Gloor

Reputation: 32725

Attributes are created by the .NET Runtime. Therefore there is no real dependency injection for them. You should try to avoid having attributes that require dependencies whenever possible. You have the following options:

  1. Service behaviors can be added without attributes. But this requires that you extend the current WCF Extension with some way to define that you want to add a service behavior for some instances in a similar way as it is currently possible for MVC Filters. This is done here: https://github.com/ninject/ninject.extensions.wcf/blob/master/src/Ninject.Extensions.Wcf/ServiceHost/NinjectServiceHost.cs
  2. You can implement an IInstance provider which searches your attributes and injects them. See https://github.com/ninject/ninject.extensions.wcf/blob/master/src/Ninject.Extensions.Wcf/NinjectInstanceProvider.cs

I'd try to go with the first option.

Upvotes: 2

Related Questions