jltrem
jltrem

Reputation: 12524

ASP.NET 5 dependency injection outside of Controllers and Views

Each tutorial or example that I've found for using DI in ASP.NET 5 only shows how it works with Controllers and Razor Views. I need to use DI for other classes but don't know the proper way to resolve types and provide an instance. Right now I have an instance of a HackyDependencyResolver that everything must reference in order to get the proper instances. I want to either access ASP.NET's service resolver or follow some other best-practice for resolving dependencies.

For example if I have

public class SomeClass
{
  public SomeClass(IUseMe useMe)
  {
  }
}

which is not an ASP.NET MVC Controller. I need a pattern for resolving a correct instance for IUseMe when SomeClass is created. Certainly I can make my own global factory, but is that the best way?

Upvotes: 3

Views: 1125

Answers (1)

MikeSW
MikeSW

Reputation: 16348

DI has nothing to do with asp.net, controllers or views. In the end all are classes. Considering that an action is an entrypoint in your app, any service you need there should be injected, The service itself has some dependencies and those will be injected automatically by the DI Container when it instantiates the controller.

All you have to do is to define your services (not every object needs injected deps) then register those services into the Di Container.

How do I resolve IUseMe so that I'm not dependent on a particular implementation?

You don't. The Di Container does that based on configuration, when the controller is instantiated. Everything has a flow, you don't just pick classes out of thin air and say "I want this created by the Di container". OK you could, but it would be the wrong approach.

The whole point of using a DI Container is not to care about instantiating services. The framework takes care of integrating with the container, your only job is to define the classes properly and to configure the container .

Upvotes: 1

Related Questions