Nuget packages: Ninject, Version 3.2.2
An obsessive focus on simplicity and ease of use. An example from their site:
1 | public class Samurai { |
When Injected Exactly Into
This binding also allows you to bind an exact instance of something WhenInjectedExactlyInto
so if you have a set of rules and your class needs a specific rule, you can inject it:
1 | Bind<IRules>().To<SomeRule>().WhenInjectedExactlyInto<ConsumerClass>(); |
Bind All Interfaces
If you have 100’s of services and they will be named as IServiceName
for the interface and ServiceName
for the implementation you can leverage refection and BindAllInterfaces
to bind these for you.
1 | var patterns = new[] |
Contextual Binding
Contextual binding allows more than one binding for a type using .Named
I dont think this is the best way to do things as the consumer (maybe a repository or service) then really has muiltiple concearns. (Well for my example anyway) The examples below were adapted from github.com/ninject and are for a scenario where 2 Launch Darkly (feature management client) projects need to be injected into the same repository. Each project has its own SDK Key so the client needs to be instantiated with its correct key.
Create an enum, for reasons :)
1 | public enum LaunchDarklyProjectEnum |
The IOC is then setup. InSingletonScope
is fine as there is no state and each request should get the same instance.
1 | Bind<ILdClient>() |
Then when resolved you indicate the name you want to use in the given context:
1 | public class LdFeatureRepository { |
- https://github.com/ninject/Ninject/wiki/Contextual-Binding
- https://launchdarkly.github.io/dotnet-server-sdk/html/T_LaunchDarkly_Client_ILdClient.htm