如何在可重用的Razor类库中的控制器中注入服务 [英] How to inject services in a controller inside a reusable Razor Class Library

查看:103
本文介绍了如何在可重用的Razor类库中的控制器中注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Razor类库来制作可在多个ASP.NET Core MVC项目中使用的可重用的复杂视图(包括其控制器和多个View组件).问题在于控制器使用依赖项注入(名为"GatewayProxy"和字符串本地化的自定义服务).将服务注入到RCL内部的控制器中的正确方法是什么?

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?

这是我的RCL的结构:

Here is the structure of my RCL:

这里是个例外:

推荐答案

您提到了如何通过将依赖项添加到主项目的Startup.cs来解决此问题的方法.但是请注意,此可重用库的任何使用者可能都不记得(或不知道)您的库需要哪些依赖项.

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.

解决此问题的方法是在您的Rcl中创建IServiceCollection的扩展名,以进行依赖项注册.

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>();
}

然后在Startup.cs中为您的MVC项目命名为扩展名

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

using Rcl.Extensions

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

这篇关于如何在可重用的Razor类库中的控制器中注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆