Amr elshaer
1 min readMay 6, 2022

--

We Can refactoring this code to achieve OCP

(Open close principle) and Single responsibility principle

______________________________________

// First

Add DbContextFactory class to return context

public class DbContextFactory

{

private readonly IDictionary<string, BaseContext> _context;

public DbContextFactory(IDictionary<string, BaseContext> context)

{

_context = context;

}

public BaseContext GetContext(string contextName)

{

return _context[contextName];

}

}

______________________________________

// Second

Add Configuration of DI of DbContextFactory

builder.RegisterType<DbOneContext>().As<BaseContext>();

builder.RegisterType<DbTwoContext>().As<BaseContext>();

builder.Register(ctx =>

{

var allContext = new Dictionary<string, BaseContext>();

allContext.Add("DbOneContext", ctx.Resolve<DbOneContext>());

allContext.Add("DbTwoContext", ctx.Resolve<DbTwoContext>());

return new DbContextFactory(allContext);

});

builder.RegisterType<BookRepository>().As<IBookRepository>();

______________________________________________

and update BookRepository to consume DbContextFactory

public class BookRepository : IBookRepository

{

DbContextFactory _contexts;

public BookRepository(DbContextFactory contexts)

{

_contexts = contexts;

}

public void Add(Book entity, string contextName)

{

var context = _contexts.GetContext(contextName);

var addedEntity = context.Attach(entity);

addedEntity.State = EntityState.Added;

context.SaveChanges();

}

public void Update(Book entity, string contextName)

{

var context = _contexts.GetContext(contextName);

var updatedEntity = context.Entry(entity);

updatedEntity.State = EntityState.Modified;

context.SaveChanges();

}

public List<Book> Get(string contextName)

{

var context = _contexts.GetContext(contextName);

return context.Books.ToList();

}

}

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

Responses (1)