Is there a way to easily inject different implementations into different layers of your application?

56 Views Asked by At

I am wondering if there is an easy way to determine the implementation of an interface by layer in ASP.NET Core.

For example, take this diagram enter image description here

  • Let's say both DataAccess.Customer and DataAccess.Employee both depend on IMySqlConnection in their repositories.
  • But both layers require different connection configuration options or implementations

Is there an easy way to have the Application Layer automatically inject different IMySqlConnections for all potential DataAccess.Customer and DataAccess.Employee repositories?

Or would there be a better way to handle this?

Thanks!

1

There are 1 best solutions below

0
Guru Stron On

If you are using or can upgrade to .NET 8 you can use freshly introduced feature allowing keyed services registration. For example:

builder.Services.AddKeyed{Lifetime}<IMySqlConnections>("Customer", (sp, key) => ...);
builder.Services.AddKeyed{Lifetime}<IMySqlConnections>("Employee", (sp, key) => ...);

And in DAL:

public class Customer 
{
    public Customer([FromKeyedServices("Customer")] IMySqlConnections connections)
    {
        // ...
    }
}

For pre .NET 8 you can create some kind of factory which will accept corresponding settings (for example, or this).