I want to inject an interface(s) of my DAL project (Core 3.1 Class Library) into my Bll Core 3.1 Project. From reading, it seems I need to use the activator Utility? Is this the case or am I wrong in my assumption? How Would I do this injection.
Lets say I have IUserBll interface in BLL and I need to inject IUserDAl interface in IUserBll.
Is there a need for a separate Project to do this (as I have done in MVC 5 with Ninject, or is there some class/function which need to be executed at some starting / entry point in the Class Library project(s)?
Injecting the BLL into and MVC project (Core 3.1.) is not an issue.
Many thanks.
Edit: Code added and error
The DAL Project code:
using System;
using BLL_Service;
namespace DAL_Service
{
public class DalClass1 : IDalInterface1
{
public string fnGetStringVal()
{
return "xx";
}
}
}
The DAL Service
using Microsoft.Extensions.DependencyInjection;
using BLL_Service;
namespace DAL_Service
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddDAL(this IServiceCollection services)
{
// Register all services as required
return services
.AddScoped<IInterfaceFromBL, DalClass1>();
}
}
}
The BLL project:
using System;
namespace BLL_Service
{
public class BLLClass1 : IInterfaceFromBL
{
public string fnGetStringVal()
{
return "";
}
}
}
If using IoC and dependency inversion, you usually have the following dependency structure between BL and DAL:
BL <--- DAL
This means:
Above implementation asserts that you are able to inject different DAL implementations into the classes of your BL. This comes handy especially in unit tests because you can easily provide test data to your BL classes through mocked implementations of the interfaces. Another (less common) scenario is that you could switch between DAL implementations and have your application access different kinds of databases (e.g. Microsoft SQL Server, Oracle, MongoDB) as long as you are able to implement the DAL interfaces for all of them.
When running the application, you need to provide the implementation to the interfaces. As the implementations in DAL are often internal, you can add an extension method in DAL that registers the services:
public static class ServiceCollectionExtensions
{
// Add parameters if required, e.g. for configuration
public static IServiceCollection AddDAL(this IServiceCollection services)
{
// Register all services as required
return services
.AddScoped<IInterfaceFromBL, ImplementationFromDAL>();
}
}
In a simple scenario, your web application often holds a reference to both BL and DAL. In your startup code (ConfigureServices
) you add a call to the extension method, e.g.:
services.AddDAL();
This way, you follow the dependency inversion principle and are able to provide the required services wherever needed.