Property injection in static class with Simple Injector

2.3k Views Asked by At

I have used dependency injection from simple injector. Now I am trying to implement property injection but the help document is not helping much.

Can anyone explain with simple example how property injection work?

I want to use it in one Utility class of Web Project, not in controller. And that class method is static.

1

There are 1 best solutions below

1
On

The documentation does not explain how to inject a static property because this is not supported in Simple Injector.

Static properties are typically a bad idea, because they hinder testability, cause Temporal Coupling, and can cause Captive Dependencies.

If a static property is required, you will have to inject the dependency yourself. You can do that in the Composition Root, right after you made all the registrations to the Container.

Example:

var container = new Container();

// Make registrations to container here:

container.Verify();

Utility.MyStaticProperty = container.GetInstance<IDependency>();

Under normal conditions, Simple Injector will detect these types of Lifestyle Mismatches, but it will not be able to do so when you inject this property yourself.