1

I have some problem with DI (Dependancy Injection). My project is on netcore 2.0 and has few layers (standard N-Tier Architecture). I'm trying to move EF Core 2 from Presentation Layer to Data Access Layer and I have created the following classes in DAL:

namespace MyProject.Infrastructure.Implementation.MySql.Contexts 
{
    public class ApplicationDbContext : DbContext
    {
        private readonly IConfiguration _configuration;

        public ApplicationDbContext(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder     optionsBuilder)
        {
            optionsBuilder.UseMySql(
                Configuration.GetConnectionString("MySql")
            );
        }

        public DbSet<Test> Test { get; set; }
    }
}

Then I prepared base class for all DAL engines:

namespace MyProject.Infrastructure.Implementation.MySql
{
    public class BaseEngine : IBaseEngine
    {
        private readonly ApplicationDbContext _context;

        protected ApplicationDbContext Db => _context;

        public BaseEngine(ApplicationDbContext context)
        {
            _context = context;
        }
    }
}

So, my common engine should look like this:

namespace MyProject.Infrastructure.Implementation.MySql
{
    public class TestEngine : BaseEngine
    {
        public List<Test> GetTestList()
        {   
            return Db.Test.ToList();
        }
    }
}

The problem is that I get error, BaseEngine needs parameter to be passed in constructor and I don't want to create all instances manually, I need somehow use Dependancy Injection that automatically creates instances of ApplicationDbContext and IConfiguration when BaseEngine and ApplicationDbContext will be created..

Any ideas?

1 Answer 1

2

Create a public interface for ApplicationDbContext, like IApplicationDbContext. Put that in the constructor for BaseEngine instead of the concrete class. Make the BaseEngine constructor protected. The BaseEngine constructor should look like:

protected BaseEngine(IApplicationDbContext context)

Then, since TestEngine is derived from BaseEngine, and BaseEngine requires a constructor argument, you have to pass that in from the TestEngine constructor like:

public TestEngine(IApplicationDbContext context) : base(context)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.