Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

enter image description here

Here is the exception:

enter image description here

like image 371
Renato Sanhueza Avatar asked Oct 21 '18 00:10

Renato Sanhueza


People also ask

What does @inject do in razor?

Dependency Injection (DI) is a technique that promotes loose coupling of software through separation of concerns.

How do I add services to Blazor WebAssembly?

If one or more common services are required by the Server and Client projects of a hosted Blazor WebAssembly solution, you can place the common service registrations in a method in the Client project and call the method to register the services in both projects.


1 Answers

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);
}
like image 193
James Sampica Avatar answered Oct 02 '22 09:10

James Sampica