I am applying dependency injection to my dotnet 3.1 project. I created a class ServiceRegister in my Application layer:
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceRegister
{
public static IServiceCollection AddApplicationServices(this IServiceCollection @this)
{
// Cart Services
@this.AddTransient<AddCustomerInformation>();
@this.AddTransient<AddToCart>();
@this.AddTransient<GetCart>();
@this.AddTransient<GetCustomerInformation>();
@this.AddTransient<Application.Cart.GetOrder>();
// Orders Services
@this.AddTransient<CreateOrder>();
@this.AddTransient<Application.Orders.GetOrder>();
// Orders Admin Services
@this.AddTransient<Application.OrdersAdmin.GetOrder>();
@this.AddTransient<GetOrders>();
@this.AddTransient<UpdateOrder>();
// Products Services
@this.AddTransient<Application.Products.GetProduct>();
@this.AddTransient<GetProducts>();
// Products Admin Services
@this.AddTransient<CreateProduct>();
@this.AddTransient<DeleteProduct>();
@this.AddTransient<GetProduct>();
@this.AddTransient<UpdateProduct>();
// Stock Admin Services
@this.AddTransient<CreateStock>();
@this.AddTransient<DeleteStock>();
@this.AddTransient<GetStock>();
@this.AddTransient<UpdateStock>();
// Users Admin Services
@this.AddTransient<CreateUser>();
return @this;
}
}
}
In my startup class I added:
services.AddApplicationServices();
When I run the app, the program errors with the following:
ArgumentException: Cannot instantiate implementation type 'Microsoft.AspNetCore.Http.ISession' for service type 'Microsoft.AspNetCore.Http.ISession'
In my addCustomerInformation class I have this constructor:
public class AddCustomerInformation
{
private readonly ISession _session;
public AddCustomerInformation(ISession session)
{
_session = session;
}
}
I am not an expert in DI, I'm assuming that I also need to register ISession somehow in my serviceRegister class, not sure how should I do that, any clues?? I tried to add this in the register:
this.AddScoped();
But no luck either, it throws an error saying that Session cannot be found, and thats after adding a reference to Microsoft.AspNetCore.Http. I'm sure I'm missing something just can't figure it out.
You should register the dependencies like this:
services.AddScoped<IInterface, Implemantation>();
You need to specify the interface
to which you register a specific implementation
. You can review the documantation for more details.
After that you inject the interface like this:
public class Service
{
private readonly IInterface _interface;
public Service(IInterface interface)
{
_interface = interface;
}
}
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.