Initializing objects using this operator in constructors - c#

As I was trying to implement code first approach using repository patterns in MVC, I have come across some difficulties as below:
I have a Interface that have few methods declared as below :
public interface IRepository
{
User Getuserdetail(int UserId);
void Save(User Obj);
void delete(int Userid);
void update(User user);
}
Then I have a Repository class which could be using the above interface to define all the methods and will create a seperate layer of Entity Framework:
public class Repository : IRepository
{
RepoDBContext _context;
Repository(RepoDBContext Context)
{
this._context = Context;
}
public User Getuserdetail(int Userid)
{
var user = _context.User.Where(m => m.id == Userid).FirstOrDefault();
return user;
}
public void Save(User user)
{
_context.User.Add(user);
_context.SaveChanges();
}
}
Now could you please check the constructor of this class. The variable this constructor is initializing is type of "RepoDBContext" and the reference type it is using to assign it is also of "RepoDBContext". Is it internally performing like below?
RepoDBContext _context=new RepoDBContext();
My RepoDBContext class is below:
public class RepoDBContext : DbContext
{
public DbSet<User> User { get; set; }
}
Moreover if is the right way to perform then how will i have to call this class in my controller to do some functionality over my user interface. Please guide regarding the same and please don't mind my english. Thanks

I think you already have an answer to the question does assigning a parameter to a field is equivalent to instantiating a new instance of that type as state in the comments and in the answer by Oskar and Kirk.
But I just want go further and try to answer this another question of yours: how will I have to call this class in my controller to do some functionality over my user interface..
If you create your structure using the Repository pattern, you wouldn't want your controllers to handle instances of your DbContext class, because if they do, what is the benefit of having a separated repository layer then? A common pattern that I see people using and I use it myself in several apps is something as follows:
IUserRepository
public interface IUserRepository
{
User GetUserDetail(int userId);
void Save(User user);
void Delete(int userId);
void Update(User user);
}
UserRepository
public class UserRepository : IUserRepository
{
public User GetUserDetail(int userId)
{
using(var _context = new RepoDBContext())
{
return _context.User.Where(m => m.id == userId).FirstOrDefault();
}
}
//other implementations here..
}
Then, you create another layer which will be your Business layer, similar to the Repository.
IUserBusiness
public interface IUserBusiness
{
User GetUserDetail(int userId);
void Save(User user);
void Delete(int userId);
void Update(User user);
}
UserBusiness
public class UserBusiness : IUserBusiness
{
private readonly IUserRepository userRepository;
//CTOR receives a Repository instance via DI
public UserBusiness(IUserRepository userRepository)
{
this.userBusiness = userBusiness;
}
public User GetUserDetail(int userId)
{
//Call repository to get User details
return this.userRepository.GetUserDetail(userId);
}
//other implementations here
}
UserController (example)
public class UserController : Controller
{
private readonly IUserBusiness userBusiness;
//Controller receives a UserBusinnes instance via DI
public UserController(IUserBusiness userBusiness)
{
this.userBusiness = userBusiness;
}
public ActionResult GetDetail(int userId)
{
//Call your "repository" to get user data
var userDetail = userBusiness.GetUserDetail(userId);
//more logic here
}
}
See the difference? Each layer of your application is concerned with one thing. You controller request data to your business layer, which may apply some business rules or validations, and finally call your repository layer which knows how to talk to the database or other storage. Your controller doesn't have any concern about how to create instances of database class or make queries. It just receive a request, ask for data and returns back to the caller.

No, assigning an existing instance of RepoDBContext to a variable is NOT the same as calling new RepoDBContext(). Assignment is just assignment and will not allocate new objects.
Off-topic:
Please also consider that C# coding guidelines suggest that method parameters should be named likeThis (that is, with initial lower case letter). This will make you code more consistent with other .Net code libraries.

Related

UnitOfWork with Repository and Entity Framework

I am working on a project with Entity Framework where i have implemented Repository pattern and DI (Microsoft Unity), now to maintain the database transactions i want to implement the UnitOfWork pattern, but i am totally confused about how shall i implement it in my current project, i google around few posts, but could not find anything doable with my existing project.
Below is the EF and Repository structure along with DI (Microsoft Unity).
Entities:
public class GenericDo
{
public DateTime CreatedDate {get;set;}
public string CreatedBy {get;set;}
}
public class UsersDo : GenericDo
{
public int UserId {get;set;}
public string Username {get;set;}
....
}
public class UserProfileDo : GenericDo
{
public int Id {get;set}
public int UserId {get;set;}
public string Address {get;set;}
....
}
Interface:
public interface IGenericDao : IGenericDao<GenericDo> {}
public interface IGenericDao<T>
{
void Add(T entity);
T Get(object Id);
....
}
public interface IUsersDao : IUsersDao<UsersDo> {}
public interface IUserProfileDao : IUserProfileDao<UserProfileDo>{}
Interface Implementation:
public class GenericDao<T> : IGenericDao<T> where T : class
{
private readonly DataContext context;
public GenericDao(DataContext _context)
{
this.context = _context;
}
public void Add(T entity)
{
context.Set<T>().Add(entity);
}
public T Get(object Id)
{
return context.Set<T>().Find(Id);
}
}
public class UsersDao : GenericDao<UsersDo>, IUsersDao
{
public UsersDao(DataContext context) : base (context){}
}
public class UserPorfileDao : GenericDao<UserProfileDo>, IUserProfileDao
{
public UserPorfileDao(DataContext context) : base (context){}
}
Dependency Injection Setup in Global.asax.
var container = this.AddUnity();
container.RegisterType<IUsersDao, UsersDao>();
container.RegisterType<IUserProfileDao, UserProfileDao>();
Now in my main webpage(ASP.Net)
public partial class Default : System.Web.UI.Page
{
private readonly IUsersDao usersDao;
private readonly IUserProfileDao userProfileDao;
public Default(IUsersDao _userDao, IUserProfileDao _userProfileDao)
{
this.usersDao = _userDao;
this.userProfileDao = _userProfileDao;
}
// Now for testing purpose, i update record.
protected void Page_Load(object sender, EventArgs e)
{
UsersDo user = usersDao.Get(1);
user.Username = "new system";
UserProfileDo userProfile = userProfileDao.Get(1);
userProfile.Address = "new address";
// Now here i am confused about setting up common Save method to update database with transaction.
}
}
EntityFramework's DbContext already implements Unit of Work, so it is not necessary to add yet another layer of abstraction to implement this.
One could even doubt if creating a Repository pattern is actually helpful if you're using Entity Framework. Instead of using a layered architecture and using a Repository, you could investigate whether it is not better to use a more sliced architecture and use the DbContext directly.
Also, what is the benefit of having a 'Generic Dao' that just delegates calls to Entity Frameworks DbContext ? It's just yet another level of abstraction which adds extra complexity but doesn't give you any added value.
Unit of work ecapsulates the database operations in a single object and keeps track of them. In Entity Framework DbContext implements this behaviour and DbSet<> implements the repository. The reason why people create their own wrappers around is to be able to swap Entity Framework for another ORM, if needed or to mock Entity Framework for testing,.
UnitOfWork pattern is used with Entity Framework.
The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).
First step is to create repositories. Repository is a class which exposes methods to business layer
Second step: You can create UnitOfWork implementation as shown below. There are properties corresponding to every repository. Then you inject Unit of Work in your business layer to use the repository methods.
public class UnitOfWork : IDisposable
{
private SchoolContext context = new SchoolContext();
private GenericRepository<Department> departmentRepository;
private GenericRepository<Course> courseRepository;
public GenericRepository<Department> DepartmentRepository
{
get
{
if (this.departmentRepository == null)
{
this.departmentRepository = new GenericRepository<Department>(context);
}
return departmentRepository;
}
}
}
refer documentation at: 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

How to call new methods from a class which implements interface

How to call a new method which is implemented in the concrete class of an interface
I am using structure map IOC container.
public interface ICompanyRepository
{
IEnumerable<Company> GetAll();
Company Get(int id);
Company Add(Company item);
bool Update(Company item);
bool Delete(int id);
}
public class CompanyRepository: ICompanyRepository
{
// Provide implementation for all interface methods
//Class CompanyRepository will also have the new method called DisplayLog
public void DisplayLog()
{
//To do
}
}
I am trying to implement DI using structure map in my Customer controller class
how can I tell the that I need methods ofcompany2 to be called?
_.Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<ICompanyRepository>();
// or
});
My code:
private readonly ICustomerRepository customerRepository;
public CustomerController(ICustomerRepository CustomerRepository)
{
customerRepository = CustomerRepository;
}
// GET: Customer
public ActionResult Index()
{
var customers = customerRepository.DisplayLog()
//Here i need to call CompanyRepository class methods DisplayLog() how can i call it here ?
// method DisplayLog() is not be shown here
return View(customers);
}
On an Interface, you can only call what is defined in the Interface - Its a definition of a "common base" of all classes that implement it. Ask yourself: What should happen if the ICompanyRepository you get is of a type that does NOT implement DisplayLog?
That means: It is not possible to call anything else than the interface methods right away.
To call DisplayLog on customerRepository there are 3 ways:
Add DisplayLog() to the Interface
Cast the customerRepository to CompanyRepository. but this will cause an exception, if the customerRepository is of any other type than CompanyRepository
Use a second interface
After all, I'm not quite sure if what you're doing is DI. In my understanding of DI it should be something like this:
public ActionResult Index(ILogDisplay display)
{
var customers = display.DisplayLog(customerRepository);
return View(customers);
}
ILogDisplay is being a new Interface for a separate class to be injected
public interface ILogDisplay
{
public YourResultType DisplayLog(ICustomerRepository);
}
In this example you actually inject a dependency (the implementation of ILogDisplay) in your class.
There's a couple of questions to raise here:
Why does the repository know how to display a log?
What does DisplayLog() mean in the context of a CustomerRepository?
Why should the controller even care about what the repository is logging?
Why is DisplayLog assigning a variable called customers when its return type is clearly void?
Fundamentally, the behaviour of your repository should be unknown to your controller, this is the essence of the Inversion of Control principle. All it cares about is that given the explicit contract provided by the interface for a repository, a method call will return customers. Logging is a concern of the repository.
A fairly traditional setup, from a DI point of view us the following:
ICompanyRepository:
public interface ICompanyRepository() {
IEnumerable<Company> GetAll();
Company Get(int id);
Company Add(Company item);
bool Update(Company item);
bool Delete(int id);
}
CustomerRepository:
public class CompanyRepository: ICompanyRepository
{
private readonly ILogger logger;
public CompanyRepository(ILogger logger) {
this.logger = logger;
}
// Provide implementation for all interface methods
public Company Get(int id) {
var customers = this.randomCustomerSource.Get(id);
this.logger.Info("Whatever you want to log here");
return customers;
}
}
CustomerController:
public class CustomerController {
private readonly ICustomerRepository customerRepository;
public CustomerController(ICustomerRepository CustomerRepository)
{
customerRepository = CustomerRepository;
}
// GET: Customers
public ActionResult Index()
{
var customers = customerRepository.GetAll()
return View(customers);
}
}
So the repository requests an Ilogger, the controller requests a ICompanyRepository, and will just call GetAll() and return the results. Usually there's a bit more involved but that's the very basic gist of a workflow for a controller that returns data.

Repository does not initialize entity data

I would like to create a Details view with entity framework data using a repository pattern.
This is my interface repository:
public interface InterfaceRepositroy: IDisposable
{
IEnumerable<SubjectContent> GetAll();
SubjectContent Get(string id);
}
This is the toher repository:
public class SubjectRepository : InterfaceRepositroy,IDisposable
{
private irfwebpage20161013070934_dbEntities2 db;
public IEnumerable<SubjectContent> GetAll()
{
return db.Set<SubjectContent>().ToList();
}
public SubjectContent Get(string id)
{
return db.Set<SubjectContent>().Find(id);
}
public void Dispose()
{
throw new NotImplementedException();
}
}
Here is my controller:
private InterfaceRepositroy subjectreposi;
public ActionResult Details(string id)
{
SubjectContent subject = subjectreposi.Get(id);
return View(subject);
}
My View is a standard details template.
It gets an error at this point in the controller:
SubjectContent subject = subjectreposi.Get(id);
I would really appreciate the help. This is like the fourth version of a repository pattern i am trying to implement but none of them worked so far. I have tried it without interface, with the instance of the subjecrepository or with different linq to sql in the repository. It either gets http error or it doesnt show the data just the names of the data.
Create constructors that initialise your data context:
public SubjectRepository()
{
db = new irfwebpage20161013070934_dbEntities2();
}
public SubjectRepository(irfwebpage20161013070934_dbEntities2 dbContext)
{
db = dbContext;
}
This allows you to either initialise your repository with no parameters which will initialise you data context or specify your own data context.
You can now use this like this:
var repo = new SubjectRepository();
SubjectContent subject = repo.Get(id);

What are better alternatives in asp.net MVC to directly accessing the database in the Controller?

Normally I do my data access by instanciating my DbContext globally in my Controller and then I use that manipulate my data.
See below:
public class UserController : Controller
{
private OrtundEntities db = new OrtundEntities();
public ActionResult Create(CreateUserViewModel model)
{
try
{
UserDataModel user = new UserDataModel
{
// map view model fields to data model ones
};
db.Users.Add(user);
db.SaveChanges();
}
catch (Exception ex)
{
// some or other error handling goes here
}
}
}
It occurs to me that this might not be the ideal way to do it in all applications but aside from implementing a web service for every project I do, I can't think of any alternatives to the above.
So what's a better way to handle the data access on larger projects where the above wouldn't be ideal?
I'm just looking for so-called "best practice" for this or that particular situation. Many opinions will differ on what's the best way so what do you think it is and why?
To help keep your controllers concise and free of direct access to your database, you can implement the repository and dependency injection patterns. For even more concise code, you can also use the unit of work pattern.
Say you had this model:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
With the help of generics, you can create an interface to provide a CRUD blueprint:
public interface IRepository<T> {
IEnumerable<T> Get();
T Get(int? i);
void Create(T t);
void Update(T t);
void Delete(int? i);
}
Then create a Repository class that implements the IRepository. This is where all your CRUD will take place:
public class PersonRepository : IRepository<Person> {
private OrtundEntities db = new OrtundEntities();
public IEnumerable<Person> Get() {
return db.Persons.ToList();
}
//invoke the rest of the interface's methods
(...)
}
Then in your controller you can invoke the dependency injection pattern:
private IRepository<Person> repo;
public PersonController() : this(new PersonRepository()) { }
public PersonController(IRepository<Person> repo) {
this.repo = repo;
}
And your controller method for, say, Index() could look like this:
public ActionResult Index() {
return View(repo.Get());
}
As you can see this has some useful benefits, including structure to your project, and keeping your controllers easy to maintain.
I think you need to read this
http://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/
Larger proyets ?
Maybe https://msdn.microsoft.com/es-es/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
I use this in some big requests.

How to implement DIP in an MVC environment?

Dependency Inversion Principle states that higher level modules should not depend on lower level modules. Both should depend on abstractions. I do understand that principle. But as I'm using ASP.NET MVC, I often get my controller methods as:
public ActionResult MyAction(string userValue)
{
User user = MyDatabase.GetUser();
if (!user.CheckSomeCondition(userValue))
{ //Something failed. Try again.
return View();
}
user.Update(userValue);
return RedirectToAction("Success");
}
I believe this violates DIP because the result of my controller depends on the User class. In this scenario, I cannot think of a way of decoupling the Controller from my User class. Is there a way to get rid of this dependency? Or is this just fine to do it this way in this scenario?
create an interface and inject an implementation on that to your mvc controller.
public interface IMyDataAccess
{
User GetUser();
}
Create your implementation now.
public class MyMongoDBDataAccess : IMyDataAccess
{
public User GetUser()
{
//return a user from my fancy db
}
}
Now in your controller
public class HomeController : Controller
{
IMyDataAccess dao;
public HomeController(IMyDataAccess myDataAccess)
{
this.dao=myDataAccess;
}
public ActionResult MyAction(string userValue)
{
User user=this.dao.GetUser();
//return something to the view as needed.
}
}
You may use any dependency injection framework like Unity to inject the desired implementation of your interface to your controller.
If you want bring in more layers like Business Layer, Service layer, follow the same thing.
If your application structure is like below, than you are implementing DIP (Dependency Inversion Principle).
DIP says that a layer in your application should depend on a interface, not by an implementation. Like below, Service is depending on IDatabase not MyDatabase
public interface IDatabase {
Update(User user);
}
public interface MyDatabase : IDatabase
{
public Update(User user) {
// update user
}
}
public interface IService {
Update(string user);
}
public class Service : IService
{
private IDatabase _database;
public Service(IDatabase database)
{
_database = database;
}
public Update(User user) {
_database.Update(user);
}
}
DIP also says that high level modules like MvcController don't need to know/depend on low level modules, MyDatabase.
public class MvcController : Controller
{
private IService _service;
private IUserValidator _userValidator;
public MvcController(IService service, IUserValidator userValidator) // depending on abstraction
{
_service = service;
_userValidator = userValidator;
}
public ActionResult MyAction(string userValue)
{
if (!_userValidator.CheckSomeCondition(userValue))
{ //Something failed. Try again.
return View();
}
User user = _service.GetUser();
user.UserValue = userValue;
_service.Update(user);
return RedirectToAction("Success");
}
}
Note:
I recommend to take a look on 3-tier-architecture doing this you will improve your understanding of SOLID and your application will be more organized.
If in your case MyDatabase is a module Higher then User than, you are not respecting DIP principles, because your Controller make uses of a lower module.
DIP or IoC says High-level modules should not depend on low-level modules. Both should depend on abstractions.
It means that High Level class should not depend on concrete class but it should depend on Interface.
But here you are talking about User class which seems a DTO (Data Transfer Object).
So In that case, You must have to use that DTO in your last layer to either return data or deal with data.
But you should not be using POCO classes provided by entity framework, Instead you should create and use your DTO classes as ViewModels.
Ups, this is how I do it when using ASP.NET Web API, not sure if this works MVC Controller. But there is Unity.MVC (v3 or v4 or v5) lib (Unity.Mvc4) that you can use!
And you can wire it up like this, you should call this code in the Application_Start event!
public static class WebApiBootstrapper
{
public static void Init(IUnityContainer container)
{
GlobalConfiguration.Configure(config =>
{
config.DependencyResolver = new WebApiDependencyResolver(container); // DI container for use in WebApi
config.MapHttpAttributeRoutes();
WebApiRouteConfig.RegisterRoutes(RouteTable.Routes);
});
// Web API mappings
// All components that implement IDisposable should be
// registered with the HierarchicalLifetimeManager to ensure that they are properly disposed at the end of the request.
container.RegisterType<IYourController, YourController>(
new HierarchicalLifetimeManager(), new InjectionConstructor(typeof(IMyDataBase)));
}
}
But before running tthis code you have to register the type mapping
container.RegisterType<IMyDatabse, MyDataBase>();
And you also have to implement the DependencyResolver class:
public class WebApiDependencyResolver : IDependencyResolver
{
protected IUnityContainer container;
public WebApiDependencyResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new WebApiDependencyResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
In your controller:
public class YourController : ApiController, IYourController
{
IDataBase _db;
public PlayGroundController(IDataBase db)
{
_db = db;
}

Categories