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.