A simple interview question.
How do interfaces help with code reusablity?
interfaces allows you to separate the implementation from the information the calling class cares about. This enables you to de-couple your classes from having intimate knowledge of classes it depends on.
Given the following interface:
public interface IRepository<T> {
void Save(T entity);
void Update(T entity);
void Delete(T entity);
}
A dependent class can be programmed against said interface and be "shielded" from the details.
public class SomeService {
private IRepository<Contact> _contactRepo;
public SomeService(IRepository<Contact> contactRepo){
_contactRepo = contactRepo;
}
}
Utilizing this pattern enables you to create different implementations of said interface:
public class LinqToSqlRepository<Contact> : IRepository<Contact>
{ /* ... */ }
public class EntityFrameworkRepository<Contact> : IRepository<Contact>
{ /* ... */ }
public class NHibernateRepository<Contact> : IRepository<Contact>
{ /* ... */ }
An interface decouples the consumer from the implementation details of a class. This helps enables reusability because the class implementing an interface can change, without needing to change the code consuming the implementation.
That's very confusing, maybe an example helps
public interface IUserAuthentication
{
public bool Authenticate(string name, string password);
}
Now I will write the consumer, it doesn't care how authentication is performed, it simply knows that it can authenticate users.
public class Consumer
{
private IUserAutentication _auth;
public Consumer(IUserAuthentication auth)
{
_auth = auth;
}
public void Working(string username, string password)
{
if (!_auth.Authenticate(username, password))
{
throw new Exception("error!");
}
}
}
The code above will work regardless of the implementation of the IUserAuthentication service. This is one way to reuse code.
Now I can implement the IUserAuthentication interface
public class AuthenticateJasons : IUserAuthentication
{
public bool Authenticate(string username, string password)
{
return username == "Jason";
}
}
public class AuthenticateNoone: IUserAuthentication
{
public bool Authenticate(string username, string password)
{
return false;
}
}
The point is that these implementations are irrelevant as far as the consumer is concerned. Also, this question is not related to ASP.NET the web framework. This is really a language/platform/framework agnostic question. The answer is the same regardless of the language you choose to implement with.
It is the Open and Close Principle, one of the important law of S.O.L.I.D Principles.
its idea is easy to change with minimum changes in the existing code. And ultimately helps with unit testing.
http://www.oodesign.com/design-principles.html
Related
I am using ef core and I am trying to implement the repository pattern as part of best practices. But I am we bit confused on the context normally I would create the context in the and inject
HomeController(WarehouseDBContext _context)
I have created my unitOfWork Class as suggested by the docs here
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application#creating-the-unit-of-work-class
However I am tad confused. It's expecting options here which is normally handled on the controller.
My UnitOfWork class
public class WarehouseUnitOfWork : IDisposable
{
private WarehouseDBContext context = new WarehouseDBContext();
private WarehouseRepository<StockItem> stockRepository;
public WarehouseRepository<StockItem> StockRepoistry
{
get
{
if (this.stockRepository == null)
{
this.stockRepository = new WarehouseRepository<StockItem>(context);
}
return stockRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
But here it is complain that it expect options which would I presume contain the connection string. I am trying to decouple my code from EF so that If I want to upgrade in the future will be easier. My WareshouseDBContext is describe below
As you can see it is expecting options. What should I pass through here?
namespace WareHouseDal.Dal {
public class WarehouseDBContext : IdentityDbContext<ApplicationUser> {
public WarehouseDBContext(DbContextOptions<WarehouseDBContext> options)
: base(options) {
}
public DbSet<WarehouseCrm> Warehouse { get; set; }
public DbSet<Company> Companies { get; set; }
}
}
When I used to create my context before I just used the singleton pattern of
private readonly WarehouseDBContext _context;
Is their something else I need to do to allow it to accept the creation of the context on the unit of work level.
Error being given is
You shouldn't create a DbContext manually. Why not injecting the DbContext in your UOW class? Then the DI will manage the life cycle of the db context. To be honest I am not a fan of adding a UOW wrapper around EF which already implements the UOW pattern.
I would recommend you to see both talks, it will change the way you structure apps forever:
https://www.youtube.com/watch?v=5OtUm1BLmG0&ab_channel=NDCConferences
https://www.youtube.com/watch?v=5kOzZz2vj2o&t=3s&ab_channel=NDCConferences
Another amazing talk about EF Core details: https://www.youtube.com/watch?v=zySHbwl5IeU&ab_channel=NDCConferences
If you want to stick with Repository pattern, please check Ardalis repository with a clear example: https://github.com/ardalis/CleanArchitecture
I agree Ardalis repository is a great tutorial/example, in case if anyone want a lite solution to implement the Repository and Unit of Work Patterns in EF 5/EF 6.
you may check out the below one, I tested it would work in EF Core 6
https://pradeepl.com/blog/repository-and-unit-of-work-pattern-asp-net-core-3-1/
I have come up with a Question, that what is the usage of Unity Container or NInject if it is handled only for a single instance of an interface.
Ex: Generally we use like this
Public Class IEmailSender
{
Public Void SendEmail();
}
Public Class SMTP: IEmailSender
{
Public Void SendEmail()
{
// Send Email Logic using SMTP
}
}
Public Class OtherSender: IEmailSender
{
Public Void SendEmail()
{
// Send Email Logic for Other Sender
}
}
Public Class Builder
{
Public Static IEmailSender CreateBuilder(string senderType)
{
if(senderType.Equals("SMTP"))
{
Return New SMTP();
}
ElseIf(senderType.Equals("OTHER"))
{
Return New OtherSender();
}
}
}
In my Screen have two buttons
#1. Send from SMTP - Event(EventArgs)
#2. Send from Other Sender - Event(EventArgs)
Have the Same Logic in two Methods
IEmailSender emailSender = Builder.CreateBuilder(button.CommandArgument)
emailSender.sendEmail();
So, How these different scenarios will be handled with Unity Configuration in Unity Block
or NInject Binder,
Your feedback will be highly appreciatable.
In Unity, You can use named instances to register and retrieve different implementations of a single interface.
First You need to register concrete types to the interface using apriopriate names:
var container = new UnityContainer();
container.RegisterType<IEmailSender, SmtpSender>("SMTP");
container.RegisterType<IEmailSender, OtherSender>("OTHER");
After this you can use it in Your code:
IEmailSender emailSender = container.Resolve<IEmailSender>(button.CommandArgument);
emailSender.SendEmail();
I'm looking at this:
public interface IAjaxCallbackEventHandler : ICallbackEventHandler
{
string CallbackResponse { get; set; }
}
}
So pages implement this interface and end up looking like this:
public partial class XPage : Page, IAjaxCallbackEventHandler {
// public because it's an interface, but really an implementation detail ;-(
public string CallbackResponse { get; set; }
// implementing underlying ICallbackEventHandler interface
public void RaiseCallbackEvent(string eventArgument)
{
try
{
CallbackResponse = SomeOperation(eventArgument);
}
catch (Exception ex)
{
CallbackResponse = ex.ToString();
}
}
// implementing underlying ICallbackEventHandler interface
public string GetCallbackResult()
{
return CallbackResponse;
}
}
As far as I can tell, this interface simply ensures that the programmer will have to think about storing the response from RaiseCallbackEvent to later be returned from the call to GetCallbackResult.
I cannot see any real benefits to this technique, since you already have to implement and think about two methods which do this.
Your thoughts - any valid benefits to this approach, or is it simply a code smell?
The interface should just define the contract and shouldn't be relied on for implying how the code should be implemented, other than to meet the requirements of the contract.
If you want to imply certain code paths, then you'd be better off having a base class which implements the interface and inherit from that as with a base class you do have a degree of control over the flow of your code, while still providing entry points for custom bits of logic to be overridden.
I am using unity, entity framework 4 with POCO classes, repository pattern for DAL and services for Business Logic control.
I also want to use Unit of Work so I can package together CRUD operations which I perform on different services and then commit them all together.
My question is what would be the proper way to inject the Unit Of Work mechanism into my application using Microsoft Unity?
I understand that I can put the IUnitOfWork together with the repository on the constructor of the proper service and then if Unity mapping is specified it would auto initiate the proper instances, but this way I do not pass the global unit of work but rather create a new instance on each level, which can't be a smart way to do it (actually the repository is initiated even before the service).
What am I missing? (Attached is constructor code as I wrote it now of service and its repository).
U also understand that I can use Unity's ParameterOverrides method to take some global instance of Unit of Work (lets say from my aspx.cs file) and pass it into the service and then into the repository. But it seems a bit lame. Is this my only option?
Thanks
public class GenericRepository<T> : IUnitOfWorkRepository, IGenericRepository<T> where T : BaseEntity, IAggregateRoot
{
private IUnitOfWork _uow;
/// <summary>
/// Returns the active object context
/// </summary>
private ObjectContext ObjectContext
{
get
{
return ObjectContextManager.GetObjectContext();
}
}
public GenericRepository(IUnitOfWork uow)
{
_uow = uow;
}
//blahhhh...
public void Add(T entity)
{
_uow.RegisterNew(entity, this);
}
public void Delete(T entity)
{
_uow.RegisterRemoved(entity, this);
}
//.....blah blah....
public void PersistCreationOf(IAggregateRoot entity)
{
this.ObjectContext.AddObject(GetEntitySetName(), entity);
}
public void PersistUpdateOf(IAggregateRoot entity)
{
// Do nothing as EF tracks changes
}
public void PersistDeletionOf(IAggregateRoot entity)
{
this.ObjectContext.DeleteObject(entity);
}
}
public class CategoryRepository : GenericRepository<XComSolutions.FB.Domain.Model.Entities.Category>, ICategoryRepository
{
public CategoryRepository(IUnitOfWork uow)
: base(uow)
{ }
}
public class CategoryService : ICategoryService
{
public int myID {get; set;}
private ICategoryRepository _categoryRepository;
private IUnitOfWork _uow;
public CategoryService(ICategoryRepository categoryRepository,
IUnitOfWork uow)
{
_categoryRepository = categoryRepository;
_uow = uow;
}
public List<Category> GetAll()
{
return _categoryRepository.GetAll();
}
}
Define an IUnitOfWorkFactory and inject that in your services:
public class Service
{
private readonly IUnitOfWorkFactory factory;
public Service(IUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void DoOperation()
{
using (UnitOfWork context = this.factory.CreateNew())
{
this.DoSomeStuff(context);
this.DoMoreStuff(context);
context.SubmitChanges();
}
}
}
What I think you need to do is to define unit of work factory. You register this factory with your DI container and you resolve for this factory every time you need your unit of work. Then you get unit of work from the factory, work with it and let it go. You often will see that you need your unit of work within a scope of single method or single class. This article discuss Unit of Work pattern in connection with Entity Framework: http://msdn.microsoft.com/en-us/magazine/dd882510.aspx
I have an interface with 3 different implementations. I register the 3 implementations as named aliases in the Web.config of the Web application using Unity Container.
Is there a way using Unity, to resolve one of the registered instance, based on some logic. the logic includes contacting a DB to decide on which implementation to be resolved.
Appreciate your help.
Regards
Bilal
You can implement the logic in an abstract factory and inject it:
public interface IMyInterface { }
public interface IMyInterfaceFactory {
IMyInterface GetMyInterface();
}
public class MyInterfaceFactory : IMyInterfaceFactory {
private readonly IUnityContainer _container;
public MyInterfaceFactory(IUnityContainer container) {
_container = container; }
IMyInterface GetMyInterface() {
var impName = Get_implementation_name_from_db();
return container.Resolve<IMyInterface>(impName);
}
}
You can create a 'router' implementation that knows how to route the requests to one of the other implementations:
// Here is a possible implementation of the router. There are
// of course many ways to do this.
public class MyRouterImpl : IMyInterface
{
List<IMyInterface> implementations = new List<IMyInterface>();
public MyRouterImpl(MyImpl1 i1, MyImpl2 i2, MyImpl3 i3)
{
this.implementations.Add(i1);
this.implementations.Add(i2);
this.implementations.Add(i3);
}
void IMyInterface.Method()
{
int indexOfImplementationToExecute =
GetIndexOfImplementationToExecute();
IMyInterface impl =
this.implementations[indexOfImplementationToExecute];
impl.Method();
}
}