Monday, February 6, 2023

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem:

I have services that are derived from the same interface.

public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService { } 
public class ServiceC : IService { }

Typically, other IoC containers like Unity allow you to register concrete implementations by some Key that distinguishes them.

In ASP.NET Core, how do I register these services and resolve them at runtime based on some key?

I don't see any Add Service methods that take a key or name parameter, which would typically be used to distinguish the concrete implementation.

    public void ConfigureServices(IServiceCollection services)
    {            
         // How do I register services of the same interface?            
    }


    public MyController:Controller
    {
       public void DoSomething(string key)
       { 
          // How do I resolve the service by key?
       }
    }

Is the Factory pattern the only option here?

Update1
I have gone though the article here that shows how to use the factory pattern to get service instances when we have multiple concrete implementations. However, it is still not a complete solution. When I call the _serviceProvider.GetService() method, I cannot inject data into the constructor.

For example consider this:

public class ServiceA : IService
{
     private string _efConnectionString;
     ServiceA(string efconnectionString)
     {
       _efConnecttionString = efConnectionString;
     } 
}

public class ServiceB : IService
{    
   private string _mongoConnectionString;
   public ServiceB(string mongoConnectionString)
   {
      _mongoConnectionString = mongoConnectionString;
   }
}

public class ServiceC : IService
{    
    private string _someOtherConnectionString
    public ServiceC(string someOtherConnectionString)
    {
      _someOtherConnectionString = someOtherConnectionString;
    }
}

How can _serviceProvider.GetService() inject the appropriate connection string? In Unity, or any other IoC library, we can do that at type registration. I can use IOption, however, that will require me to inject all settings. I cannot inject a particular connection string into the service.

Also note that I am trying to avoid using other containers (including Unity) because then I have to register everything else (e.g., Controllers) with the new container as well.

Also, using the factory pattern to create service instances is against DIP, as it increases the number of dependencies a client has details here.

So, I think the default DI in ASP.NET Core is missing two things:

  1. The ability to register instances using a key
  2. The ability to inject static data into constructors during registration

 Answer:

We did a simple workaround using Func when I found myself in this situation.

Firstly declare a shared delegate:

public delegate IService ServiceResolver(string key);

Then in your Startup.cs, setup the multiple concrete registrations and a manual mapping of those types:

services.AddTransient<ServiceA>();
services.AddTransient<ServiceB>();
services.AddTransient<ServiceC>();

services.AddTransient<ServiceResolver>(serviceProvider => key =>
{
    switch (key)
    {
        case "A":
            return serviceProvider.GetService<ServiceA>();
        case "B":
            return serviceProvider.GetService<ServiceB>();
        case "C":
            return serviceProvider.GetService<ServiceC>();
        default:
            throw new KeyNotFoundException(); // or maybe return null, up to you
    }
});

And use it from any class registered with DI:

public class Consumer
{
    private readonly IService _aService;

    public Consumer(ServiceResolver serviceAccessor)
    {
        _aService = serviceAccessor("A");
    }

    public void UseServiceA()
    {
        _aService.DoTheThing();
    }
}

Keep in mind that in this example the key for resolution is a string, for the sake of simplicity and because OP was asking for this case in particular.

But you could use any custom resolution type as key, as you do not usually want a huge n-case switch rotting your code. Depends on how your app scales.


How to store and retrieve objects in Session state in ASP.NET Core

 Problem:

How would I add EmployeeId and DesignationId to an object and then retrieve it from Session state afterward?

Here is my login controller Code:

DataTable dt = sql.GetDataTable("select * from EmpDetails where EmailId = '" + EmailId + "'");
string strempstatus = dt.Rows[0]["Status"].ToString();
string EmpStatus = strempstatus.TrimEnd();

//Models.UserDetails detail = new Models.UserDetails();

if (EmpStatus == "Verified")
{
    //i want to create object which store below two variable value
    string EmployeeId = dt.Rows[0]["Id"].ToString();
    string DesignationId = dt.Rows[0]["D_Id"].ToString();

    //I want to stored object in below session
    HttpContext.Session.SetString("EmployeeData", EmployeeId);

    HttpContext.Session.SetInt32("EmployeeID", Convert.ToInt32(EmployeeId));
    //For Destroy Session
    //HttpContext.Session.Remove("EmployeeID");

    Int32? Saved = HttpContext.Session.GetInt32("EmployeeID");

    if (DesignationId == "1")
    {
        return RedirectToAction("Index", "AdminDashboard");
    }
    else
    {
        return RedirectToAction("Index", "UserDashboard");
    }
}


----------------------------------------------------------------------------------------------------------------------------

Answer:


In your Startup.cs, under the Configure method, add the following line:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}

And under the ConfigureServices method, add the following line:

public void ConfigureServices(IServiceCollection services)
{
  //Added for session state
  services.AddDistributedMemoryCache();
   
  services.AddSession(options =>
  {
  options.IdleTimeout = TimeSpan.FromMinutes(10);               
  });
}

In order to store complex objects in your session in .NET Core, follow the following steps:

Create a model class of your object type (in your case EmployeeDetails):

public class EmployeeDetails
{
    public string EmployeeId { get; set; }
    public string DesignationId { get; set; }
}

Then create a SessionExtension helper to set and retrieve your complex object as JSON:

public static class SessionExtensions
{
  public static void SetObjectAsJson(this ISession session, string key, object value)
   {
     session.SetString(key, JsonConvert.SerializeObject(value));
   }
    
   public static T GetObjectFromJson<T>(this ISession session, string key)
   {
     var value = session.GetString(key);
     return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
   }
}

Then finally set the complex object in your session as:

var employee = new EmployeeDetails();
employee.EmployeeId = "1";
employee.DesignationId = "2";

HttpContext.Session.SetObjectAsJson("EmployeeDetails", employee);

To retrieve your complex object in your session:

var employeeDetails = HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
int employeeID = Convert.ToInt32(employeeDetails.EmployeeId);
int designationID= Convert.ToInt32(employeeDetails.DesignationId);

EDIT:

I have seen quite a bit of questions where the Session data is not accessible on the View, so I am updating my answer on how to achieve this also. In order to use your Session variable on the View, you need to inject IHttpContextAccessor implementation to your View and use it to get the Session object as required:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
    //Get object from session
    var mySessionObject = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
 }

<h1>@mySessionObject.EmployeeId</h1>
<h1>@mySessionObject.DesignationId</h1>


How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...