Iam trying to make a generic class that receives a Type. this generic class will need to create an instance from the received type. The received type has two overloads in his constructor, one constructor can receive a parameter but the other one doesn't have any parameter. y generic class need sometimes to create object from received class without parameters in constructor and other times with parameter in constructor.
A simple view in my generic class :
public sealed class Repo<TContext> : IRepo<TContext>, IDisposable where TContext : DbContext, new() { #region properties /// <summary> /// Private DBContext property /// </summary> private DbContext _Context { get; } = null; /// <summary> /// Determine if Lazy Loading either activate or not /// </summary> private bool _LazyLoaded { get; set; } #endregion #region Construcors public Repo(bool LazyLoaded) { _Context = new TContext(); _LazyLoaded = LazyLoaded; _Context.ChangeTracker.LazyLoadingEnabled = LazyLoaded; } public Repo(DbContext context,bool LazyLoaded) { _Context = context; _LazyLoaded = LazyLoaded; _Context.ChangeTracker.LazyLoadingEnabled = LazyLoaded; } at now everything's good, but when I add a third constructor in my generic class for creating an instance from received TContext but this time with his (TContext) constructor that need one parameter,
public Repo(DbContextOptionsBuilder<TContext> optionsBuilder,bool LazyLoaded) { _Context = new TContext(optionsBuilder); _LazyLoaded = LazyLoaded; _Context.ChangeTracker.LazyLoadingEnabled = LazyLoaded; } I got this error:
Error CS0417 'TContext': cannot provide arguments when creating an instance of a variable type MyTypeName
The Question:
My question is how I can create an instance from TContext using his constructor that receive parameters ?
thank you in advance.
new()to do this. You could use reflection to create the new object, but that makes your code a little fragile. It would probably be better to pass in some kind of factory method that created the object.DbContexttype you want to build. I'm wondering though... why do you need 3 ways to receive aDbContext? Something seems fishy in your setup.new()constraint, .net will use the following IL Code[System.Runtime]System.Activator::CreateInstance<!!0/*T*/>()