How to inject services in a controller inside a reusable Razor Class Library

六眼飞鱼酱① 提交于 2019-12-08 04:25:56

问题


I am using a Razor Class Library for making a reusable complex View (which includes its controller and several View Components) that can be used across several ASP.NET Core MVC projects. The problem is that the controller use dependency injection (a custom service called "GatewayProxy" and string localization). What is the correct way to inject services into a controller inside a RCL?

Here is the structure of my RCL:

Here is the exception:


回答1:


You mentioned how you fixed this by adding the dependencies to Startup.cs of your main project. But consider that any consumer of this reuseable library may not remember (or know) what dependencies are needed for your library.

Something you can do to solve this is to create an extension off of IServiceCollection in your Rcl that does the dependency registration.

public static void AddMyRclServices(this IServiceCollection serviceCollection, IConfiguration config)
{
    serviceCollection.AddTransient<IRclService1, RclService1>();
    serviceCollection.AddScoped<IRclService2, RclService2>();
}

Then in Startup.cs for your MVC project call the extension

using Rcl.Extensions

public void ConfigureServices(IServiceCollection services)
{
    services.AddMyRclServices(config);
}


来源:https://stackoverflow.com/questions/52911182/how-to-inject-services-in-a-controller-inside-a-reusable-razor-class-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!