TheBreadman TheBreadman - 3 months ago 16
C# Question

Dependency Injection in asp.net 5 custom classes, what is the correct way?

Trying to understand DI.

What is correct way to use services/dependency objects in custom classes?

Do i need to create each class as service and add to dependency objects?

Or should I be using [FromServices] (previously, [Active] before beta4 ) attribute.

or is there is a service object I should be passing to access them?

What trying to understand, is how i properly code my own classes to use the DI like the controllers etc.

Answer

[FromServices] is just an MVC concept. It is not available to other parts of the ASP.NET 5 stack.

If you want to pass dependencies down the chain you have a few options:

  1. Pass the service provider. This is quite an anti-pattern because your objects need to depend on the DI container and you are not really inverting the control.
  2. Pass interfaces in constructors. The "pure" DI but you might end up with a parameter nightmare (objects that take 10 arguments in constructor).
  3. Similar to the previous one but group dependencies in factories. More DI aligned and less parameter nightmare but it can create a factory nightmare.
  4. Inject only top large level objects (for example: repositories, entire systems, etc). This approach is a nice tradeoff between dependency nightmare and too much coupling. Of course, the systems that get injected should be independent from each other. Also, each system could have its own DI container inside.

!! Don't confuse DI with Configuration. DI makes sense when you have a dependency on a contract. Configuration useful when you need some information that is specific to the current implementation.

Example: if you have an IRepository then you shouldn't inject the connection string because connection strings are specific to a system that you connect to. There are cases when connection strings don't make sense. For example, an InMemoryRepository will not require a connection string and thus that is not a common dependency for all implementations.