简体   繁体   中英

DI outside the constructor

Can we request dependencies on the fly in .NET Core? Something like:

public void MyMethod() {
    var dep = DependencyMagic.Instantiate<MyDependency>();
}

I'm not interested in a 3rd party solution, but feel free to comment on them if it completes your answer. I'm just using the DI built into .NET Core. I can't use Activator because I don't know what the signature of the dependency's constructor will be.

You need to use instance of System.IServiceProvider . It defines next method:

// Gets the service object of the specified type.
public object GetService(Type serviceType)

in .NET Core this extension method also is provided:

public static T GetService<T>(this IServiceProvider provider)

and Microsoft.Extensions.DependencyInjection.IServiceScope.ServiceProvider ( definition ) is the default implementation of IServiceProvider interface.

If you application is an ASP.NET Core, then having HttpContext you can retrieve IServiceProvider instance. From official documentation:

The services available within an ASP.NET request from HttpContext are exposed through the RequestServices collection.

在此处输入图片说明

Request Services represent the services you configure and request as part of your application. When your objects specify dependencies, these are satisfied by the types found in RequestServices, not ApplicationServices.

Generally, you shouldn't use these properties directly, preferring instead to request the types your classes you require via your class's constructor, and letting the framework inject these dependencies. This yields classes that are easier to test (see Testing) and are more loosely coupled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM