Simple repository asp.net mvc with entity framework - asp.net

I am about to start a small/medium sized project. I am by no means a software architect. But i tend to question every move i make at times. Since i want to do things correct.
I found a way to implement a simple repository, and i wanted to know if this is a "correct" way of doing it. I came to this solution, since i know what is going on, and not taking in something to complex before i have the knowledge :)
Here it goes.
Unit of work
Where i make sure i to keep all my repositories under the same dbcontext. In my uof i can access all repo's when calling it from the controller.
public class UnitOfWork : IDisposable
{
private ContactRepository _contactRepo;
private ApplicationDbContext _entities;
public UnitOfWork(ApplicationDbContext entities)
{
_entities = entities;
}
public ContactRepository ContactRepo
{
get
{
if (_contactRepo == null)
{
_contactRepo = new ContactRepository(_entities);
}
return _contactRepo;
}
}
public void Save()
{
_entities.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
ContactRepository
This is a short example of a repository, where it recieves the dbcontext and uses it to grab whatever data i want
public class ContactRepository
{
private ApplicationDbContext _entities;
public ContactRepository(ApplicationDbContext entities)
{
_entities = entities;
}
public IEnumerable<Contact> GetAll()
{
return _entities.Contacts;
}
}
Controller
Short example of controller
public class ContactController : Controller
{
UnitOfWork uow = new UnitOfWork(new ApplicationDbContext());
public ActionResult Index()
{
var contacts = uow.ContactRepo.GetAll();
return View(contacts);
}
protected override void Dispose(bool disposing)
{
uow.Dispose();
base.Dispose(disposing);
}
}
In this way i will have access to all my repositories under the same dbcontext which i was aiming for.
I know things can be done smarter/different. With for example a extendable generic repo. But in this case i am aiming for something simple and understandable. But still dont want to make a huge mistake, if there is a major flaw.
Do you see any major flaws with this way of handling data trough entity framework?

If you're aiming for something simple then just use Entity Framework but if you're going to use the repository pattern I would encourage you to do it properly.
Two of the biggest motivators for using repository are:
You want to simplify CRUD applications to your database.This is
done through the use of interfaces and generics
You want to the ability to test the business logic in isolation
from external dependencies.Again, this is done through the use of
interfaces
Below will take you two minutes to implement but then at least you know you're doing it right, because at the moment you're trying to implement a great pattern in an ineffective way.
Generic interface:
public interface IRepository<T>
{
T GetById(int id);
IEnumerable<T> List();
IEnumerable<T> List(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
void Update(T entity);
}
Generic repository:
public abstract class EntityBase
{
}
public class DBRepository<T> : IRepository<T> where T : EntityBase
{
private readonly DbContext _dbContext;
public DBRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public virtual T GetById(int id)
{
return _dbContext.Set<T>().Find(id);
}
public virtual IEnumerable<T> List()
{
return _dbContext.Set<T>().AsEnumerable();
}
public virtual IEnumerable<T> List(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
return _dbContext.Set<T>()
.Where(predicate)
.AsEnumerable();
}
public void Add(T entity)
{
_dbContext.Set<T>().Add(entity);
}
public void Update(T entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
}
public void Delete(T entity)
{
_dbContext.Set<T>().Remove(entity);
}
Unit of work:
public class UnitOfWork : IDisposable
{
private bool disposed = false;
private ApplicationDbContext context = new ApplicationDbContext();
private IRepository<Contact> _contactRepository;
public IRepository<Contact> ContactRepository
{
get
{
if (this._contactRepository == null)
this._contactRepository = new DBRepository<Contact>(context);
return _contactRepository;
}
}
public void Save()
{
context.SaveChanges();
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
context.Dispose();
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}

Related

How do you abstract page session properties?

I was following this example
example code:
public class Global : HttpApplication
{
private Poster _posterDetails;
private Posting _postingDetails;
private Property _propertyDetails;
protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Session == null) return;
_posterDetails = HttpContext.Current.Session["Poster"] as Poster;
_postingDetails = HttpContext.Current.Session["Posting"] as Posting;
_propertyDetails = HttpContext.Current.Session["Property"] as Property;
}
}
these session variables are littered throughout the app and I need to abstract the retrieval of them. Say, later I get them from a db instead of the current session.
Session is baked into the Page or Context. How do I inject that dependency into the concrete implementation of a possible current property getter.
Create an abstraction around HttpContext:
public interface IHttpContextFactory
{
HttpContextBase Create();
}
public class HttpContextFactory
: IHttpContextFactory
{
public HttpContextBase Create()
{
return new HttpContextWrapper(HttpContext.Current);
}
}
Then inject it into a specialized service for these settings.
public interface ISettings
{
T GetValue<T>(string key);
void SetValue<T>(string key, T value);
}
public class ContextSettings
: ISettings
{
private readonly IHttpContextFactory httpContextFactory;
private HttpContextBase context;
public RequestCache(
IHttpContextFactory httpContextFactory
)
{
if (httpContextFactory == null)
throw new ArgumentNullException("httpContextFactory");
this.httpContextFactory = httpContextFactory;
}
protected HttpContextBase Context
{
get
{
if (this.context == null)
{
this.context = this.httpContextFactory.Create();
}
return context;
}
}
public virtual T GetValue<T>(string key)
{
if (this.Context.Session.Contains(key))
{
return (T)this.Context.Session[key];
}
return default(T);
}
public virtual void SetValue<T>(string key, T value)
{
this.Context.Session[key] = value;
}
}
It will later be possible to replace the service with another storage mechanism by implementing ISettings and providing different constructor dependencies. Note that changing the constructor signature does not require a different interface.
That said, you should provide another service (or perhaps more than one) that takes ISettings as a dependency so you can make explicit properties. You should aim to provide focused sets of related properties for specific purposes. Your application also shouldn't have to know the type of property in order to retrieve its value - it should just call a property that hides those details.
public class SomeSettingsService: ISomeSettingsService
{
private readonly ISettings settings;
public SomeSettingsService(ISettings settings)
{
if (settings == null)
throw new ArgumentNullException("settings");
this.settings = settings;
}
public Poster Poster
{
get { return this.settings.GetValue<Poster>("Poster"); }
set { this.settings.SetValue<Poster>("Poster", value); }
}
public Posting Posting
{
get { return this.settings.GetValue<Posting>("Posting"); }
set { this.settings.SetValue<Posting>("Posting", value); }
}
public Property Property
{
get { return this.settings.GetValue<Property>("Property"); }
set { this.settings.SetValue<Property>("Property", value); }
}
}
Not sure if this is what you are asking... What I often do is create a service:
public interface ISessionService
{
object Get(string key);
void Save(string key, object value);
}
And then I implement this, which calls HttpContext.Current.Session[key] and returns the value. It shouldn't be hard to create a Get<T>(string key) to return an object either. Break all of your dependencies to use this (which is the hard part).
There is no seamless way to break the dependency... it has to be through a manual change.

ASP.NET MVC - Abstraction between Data and Object Layers

I am using ASP.NET EntityFramework MVC (All Latest) with Visual Studio 2013.
I am attempting to come up with a unifying means of standardizing the abstraction between my object and data layer.
I know that many people like to use the IRepository pattern with MVC. My biggest issue with this is that it forces you to create and maintain a second object type (The Repository) for each of the objects that you want to maintain. My solution has been to combing the IRepository method with a Static Factory pattern to make a Static Repository, for instance:
public class SiteDatabase : DbContext
{
// Singleton
private static SiteDatabase _Instance;
public static SiteDatabase Instance
{
get
{
if (_Instance == null)
{
_Instance = new SiteDatabase();
}
return _Instance;
}
}
public DbSet<User> Users { get; set; }
}
public class User : IUser
{
public static User Create(string UserName)
{
User item = new User();
item.UserName = UserName;
SiteDatabase.Instance.Users.Add(item);
return item;
}
public static User Find(string UserName)
{
return SiteDatabase.Instance.Users.SingleOrDefault(x => x.UserName == UserName);
}
public static User[] All()
{
return SiteDatabase.Instance.Users.ToArray();
}
public string Id { get; set; }
public string UserName { get; set; }
protected User()
{
Id = Guid.NewGuid().ToString();
}
public void Delete()
{
SiteDatabase.Instance.Users.Remove(this);
}
}
public class Page
{
public static Page Create(string PageName)
{
...
}
public static Page Find(string PageName)
{
...
}
public static Page[] All()
{
...
}
...
public void Delete()
{
...
}
}
My question is: will this pattern cause me to miss out on any built-in functionality that the normal repository pattern would allow me to capture?
The non-static methods could be handled with an interface, but what about the static methods? Is there any way to have a base class that ensures that static methods will exist in derived classes?

DbSet, DbContext, EntityFramework

I am new to ASP.NET and very new to EF. I am trying to develop an application and after reading some sites I've decided I'm going to create a 3-tier application (DAL, BL, a website as the frontend).
For the DAL layer I've taken inspiration from here
http://codefizzle.wordpress.com/2012/07/26/correct-use-of-repository-and-unit-of-work-patterns-in-asp-net-mvc/
public interface IGenericRepository<T> where T : class
{
void Add(T a);
}
public interface IUnitOfWork:IDisposable
{
IGenericRepository<UserInfo> UserInfoRepository { get; }
void Commit();
}
public class EfGenericRepository<T> : IGenericRepository<T> where T : class
{
private DbSet<T> _dbSet;
public EfGenericRepository(DbSet<T> dbSet)
{
_dbSet = dbSet;
}
public void Add(T a)
{
_dbSet.Add(a);
}
}
public class EfUnitOfWork : DbContext, IUnitOfWork
{
private readonly EfGenericRepository<UserInfo> _userInfoRepo;
public DbSet<UserInfo> UserInfos { get; set; }
public EfUnitOfWork()
{
_userInfoRepo = new EfGenericRepository<UserInfo>(UserInfos);
}
public IGenericRepository<UserInfo> UserInfoRepository
{
get { return _userInfoRepo; }
}
public void Commit()
{
this.SaveChanges();
}
}
and my BL looks like this:
public interface IBussinessLogic
{
void AddUserInfo(string c);
}
public class BusinessLogic: IBussinessLogic
{
private IUnitOfWork _unitOfWork;
public BusinessLogic()
{
_unitOfWork = new EfUnitOfWork();
}
public void AddUserInfo(string c)
{
_unitOfWork.UserInfoRepository.Add(new UserInfo()
{
Address = c
});
_unitOfWork.Commit();
}
}
Now I am using web-forms but I don't think that should be an issue.
On click i execute this:
IBussinessLogic businessLogic = new BusinessLogic();
businessLogic.AddUserInfo(address.Text);
But nothing happens,my data is not saved in the db.
Can anyone please help me?

Windsor ComponentNotFoundException IHttpControllerActivator

I have tried to implement Castle Windsor into my ASP.NET Web API project by following the guide by Mark Seemann. But when I try to run the code it gives me a ComponentNotFoundException exception. I mean that I should have registered the dependency right.
I really hope that someone has a solution to my problem. I have tried to search for a solution but with out any luck.
Global.asax
public class WebApiApplication : System.Web.HttpApplication
{
private readonly IWindsorContainer _container;
public WebApiApplication()
{
_container = new WindsorContainer().Install(new ControllerInstaller());
}
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(_container));
}
public override void Dispose()
{
_container.Dispose();
base.Dispose();
}
}
IHttpControllerActivator implementation
public class WindsorCompositionRoot : IHttpControllerActivator
{
private readonly IWindsorContainer _container;
public WindsorCompositionRoot(IWindsorContainer container)
{
_container = container;
}
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var controller =
(IHttpController)_container.Resolve(controllerType);
request.RegisterForDispose(
new Release(
() => _container.Release(controller)));
return controller;
}
private class Release : IDisposable
{
private readonly Action release;
public Release(Action release)
{
this.release = release;
}
public void Dispose()
{
release();
}
}
}
ControllerInstaller
public class ControllerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<IGymnastDataAccess>().ImplementedBy<GymnastDataAccess>());
}
}
Controller
public class GymnastController : ApiController
{
private readonly IGymnastDataAccess _gymnastDataAccess;
public GymnastController(IGymnastDataAccess gymnastDataAccess)
{
_gymnastDataAccess = gymnastDataAccess;
}
public IEnumerable<string> Get()
{
_gymnastDataAccess.Load();
return new string[] { "value1", "value2" };
}
}
Castle Windsor do not support automatic resolve of concrete classes out of the box, so you should register your controller class in container:
container.Register(Component.For<GymnastController>());
or implement ILazyComponentLoader like here to get automatic resolve of concrete classes.

Create a log everytime When methods in an interface class are called

I want to update a log file(txt) everytime when methods in a an interface class are called?
Is there any way to do this other than writing code in every method to create log?
Here's my 30 mins. you'll have to implement the logging code somewhere so you have to create another abstraction for your code. thus an abstract class is needed. i think. this is very quick and dirty.
public interface IService<T>
{
List<T> GetAll();
bool Add(T obj);
}
then you'll need the abstract class where you'll need to implement your logging routine
public abstract class Service<T> : IService<T>
{
private void log()
{
/// TODO : do log routine here
}
public bool Add(T obj)
{
try
{
log();
return AddWithLogging(obj);
}
finally
{
log();
}
}
public List<T> GetAll()
{
try
{
log();
return GetAllWithLog();
}
finally
{
log();
}
}
protected abstract List<T> GetAllWithLog();
protected abstract bool AddWithLogging(T obj);
}
as for your concrete classes
public class EmployeeService : Service<Employee>
{
protected override List<Employee> GetAllWithLog()
{
return new List<Employee>() { new Employee() { Id = 0, Name = "test" } };
}
protected override bool AddWithLogging(Employee obj)
{
/// TODO : do add logic here
return true;
}
}
public class CompanyService : Service<Company>
{
protected override List<Company> GetAllWithLog()
{
return new List<Company>() { new Company() { Id = 0, Name = "test" } };
}
protected override bool AddWithLogging(Company obj)
{
/// TODO : do add logic here
return true;
}
}
public class Employee
{
public int Id {get;set;}
public string Name { get; set;}
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
then on your implementation you can just..
static void Main(string[] args)
{
IService<Employee> employee = new EmployeeService();
List<Employee> employees = employee.GetAll();
foreach (var item in employees)
{
Console.WriteLine(item.Name);
}
IService<Company> company = new CompanyService();
List<Company> companies = company.GetAll();
foreach (var item in companies)
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
hope this helps!
I think you would have to use Aspect Oriented Programming to achieve that. Read http://www.sharpcrafters.com/aop.net
I think you meant class (instead of interface)
Two options I can think of:
Implementing INotifyPropertyChanged which is in lines of writing code in every method
or
to adopt on of the AOP frameworks in the article http://www.codeproject.com/KB/cs/AOP_Frameworks_Rating.aspx if that is not a major leap

Resources