0

Using Asp.Net Core 3 have the following method:

public static void AddLiteContext<TContext, TContextMapper>(this IServiceCollection services, String connection) 
  where TContext : ILiteContext 
  where TContextMapper : LiteContextMapper {

}

Inside this method I need to the following:

services.AddTransient<Context>(x => new Context(connection, new ContextMapper()));

But I need to create the instances of Context and ContextMapper based on the generics:

ILiteContext 
LiteContextMapper

Note that class Context and class ContextMapper are implementations of these generics:

public class Context : ILiteContext { }

public class ContextMapper : LiteContextMapper { }

I use the method as follows:

services.AddLiteContext<Context, ContextMapper>(myConnection); 

How can I do this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • I'm not sure if we're aligned on what a generic is, based on the "Note that class Context and class ContextMapper are implementations of these **generics**". Do you mean *interfaces*? Theres not a single generic type on your code, I only see thow generic methods. – Pablo Recalde Apr 17 '20 at 15:42
  • @PabloRecalde I am not sure what you mean but I think I need to create an instance of LiteContextMapper and then an instance of ILiteContext using in the constructor the instance of LiteContextMapper created before. And then I can use this in AddTransiente method. Does this makes sense? – Miguel Moura Apr 17 '20 at 15:48
  • EntityFrameworkCore has its own extensions to IServiceCollection to register the context and its persistency provider. Please take a look here https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&tabs=visual-studio#startupcs – Pablo Recalde Apr 17 '20 at 17:52

0 Answers0