2

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.

Steven
  • 166,672
  • 24
  • 332
  • 435
Dhwani
  • 7,484
  • 17
  • 78
  • 139
  • What is not clearly explained? It explains how the behavior is for some other ones, why it's not enabled by default and how you can overwrite it. Is your class static or the method you wish to call? If it's the class, then I don't see a possibility for you to inject it. Maybe you should add it as part of the constructor injection of your controller? – Icepickle Sep 27 '17 at 06:42
  • The method is static. And that class method directly call from Layout so no controller will be in picture. – Dhwani Sep 27 '17 at 06:53
  • 2
    It would be good to update your question and provide some more context. Show your use case, show the class you wish to inject the dependency in. Describe what that dependency is. Show how you intend to use this property. – Steven Sep 27 '17 at 07:08

1 Answers1

4

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.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • `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.` - Any example for the same? – Dhwani Sep 27 '17 at 08:13