Should factories persist entities they build? Or is that the job of the caller? Pseudo Example Incoming:
public class OrderFactory
{
public Order Build()
{
var order = new Order();
....
return order;
}
}
public class OrderController : Controller
{
public OrderController(IRepository repository)
{
this.repository = repository;
}
public ActionResult MyAction()
{
var order = factory.Build();
repository.Insert(order);
...
}
}
or
public class OrderFactory
{
public OrderFactory(IRepository repository)
{
this.repository = repository;
}
public Order Build()
{
var order = new Order();
...
repository.Insert(order);
return order;
}
}
public class OrderController : Controller
{
public ActionResult MyAction()
{
var order = factory.Build();
...
}
}
Is there a recommended practice here?
As a general rule the factory has only one responsibility: create an instance and return it. I would not mix in persistence. I would view it as the responsibility of another class. In this case, it would be the controller.
The Factory's main purpose is the creation of objects. Once that object has been created it's up to you to decide what you want to do with it.
The only case where this would be different is if there's also a requirement that only once instance of the created object should exist, in which case you'll have some kind of pseudo-factory-singleton hybrid pattern going on.
If you decide to use a factory for singleton objects, you will need to manage the persistence of the singleton object. Other than that, I can't see why you'd want to have factories manage persistence.
Actually, having factories manage persistence - with the exception of when singletons are involved - would lead to the very opposite of proper separation of concerns, which is the raison d'etre for using factories in the first place.
Related
If I have a service that relies on data obtained through runtime, what is the best way to inject it into a class?
I have an Order class:
class Order {
string OrderID { get; set; }
string CustomerName { get; set; }
...
}
I want to encapsulate a lot of logic from the database, so I have a service:
class OrderService {
private readonly IOrderRepository _orderRepository;
private readonly IOrder _order;
public OrderService(IOrderRepository orderRepository, IOrder order) {
_orderRepository = orderRepository;
_order = order;
}
// some methods that compile data from the repository
public bool CheckAlreadyExists() { ... }
public string GetLatestShippingStatus() { ... }
...
...
public void Create() { ... }
}
Controller logic:
public class OrderController {
private readonly IOrderRepository _orderRepository
public OrderController(IOrderRepository orderRepository)
{
orderRepository = _orderRepository
}
public IActionResult Create(Order order)
// this is bad because now I have a dependency on IOrderRepository and OrderService
OrderService orderService = new OrderService(orderRepository, order)
if (!orderService.CheckAlreadyExists()) {
orderService.Create();
}
end
}
The two options I am aware of:
Refactor the code to pass runtime data into each of the functions instead
Create a factory OrderServiceFactory
I do not want to have to pass the parameter into every method which all rely on the same object. It seems like overkill to create a factory for every time I need this pattern, which seems like it should be a common use-case.
I think I'm fundamentally misunderstanding something.
Is there a pattern that I'm unaware of?
Could I create a service that keeps track of the runtime data?
Or am I just being stubborn and should create a factory?
I would simply comment but I don't have the reputation. Long story short, you need to be passing runtime data to OrderService. Read the link provided by Nkosi.
Having OrderService instantiated with a particular Order does not make sense. That means that you have to new up OrderService for every Order you get. Instead, OrderService should have per-lifetime scope. Ie - you can use the same instance of OrderService with multiple Orders. It's not overkill to pass runtime data to every method of a service; it's standard. You're overcomplicating things by forcing your service to rely on an instance of the object it is servicing. And your OrderRepository should not be injected in your controller at all. Use the service to call repository methods.
I have a data access layer which returns repositories.
For example, I have the following repository interfaces:
I have Entity Framework implementations of these repositories. These implementations get injected at a runtime with Ninject.
I have One controller with multiple repositories given below
IUploadRepository _uploadRepository;
ISalesRepository _salesRepository;
ITRSalesRepository _trsalesRepository;
ILocalPurchaseRepository _localRepository;
with single controller named -HomeController
In order to functional operation , I need to use DBContext into implementation thats why I implement all those interface like given below:
public class UploadRepository : IUploadRepository
{
private readonly XMANEntities _entities;
public UploadRepository(XMANEntities entities)
{
_entities = entities;
}
*here goes all implementation with context for specific*
}
Here now I have a constructor within a HomeController which looks this:
public class HomeController : Controller
{
private IUploadRepository uploadRepository;
public HomeController()
{
this.uploadRepository = new UploadRepository(new XMANContext());
}
public HomeController(IUploadRepository uploadRepository)
{
this.uploadRepository = uploadRepository;
}
}
How can I use others in this controller.Is it bad practice to inject multiple repo's into a controller?
i have tried this way like given below:
public HomeController() : this(new UploadRepository(
new XMANEntities()), new SalesRepository(new XMANEntities()),
new TRSalesRepository(
new XMANEntities()), new LocalPurchaseRepository(new XMANEntities()))
{
}
public HomeController(UploadRepository uploadRepository, SalesRepository salesRepository,
TRSalesRepository trsalesRepository, LocalPurchaseRepository localPurchaseRepository)
{
this.uploadRepository = uploadRepository;
this.salesRepository = salesRepository;
this.trsalesRepository = trsalesRepository;
this.localPurchaseRepository = localPurchaseRepository;
}
It's perfectly acceptable to inject multiple dependencies on an object. However, avoid it as much as possible (Except for transactional objects) to prevent mixing of responsibilities. An approach that you can look at is stored procedures.
private IUploadRepository _uploadRepository;
private ISalesRepository _salesRepository;
private ITRSalesRepository _trsalesRepository;
private ILocalPurchaseRepository _localRepository;
public HomeController(
IUploadRepository uploadRepository,
ISalesRepository salesRepository,
ITRSalesRepository trsalesRepository,
ILocalPurchaseRepository localRepository
)
{
this._uploadRepository = uploadRepository;
this._salesRepository= salesRepository;
this._trsalesRepository= trsalesRepository;
this._localRepository= localRepository;
}
Recently i've working on an ASP.NET MVC5 project, i dived right in and wrote all my logic right in the action method and after doing this for a few controllers i've noticed that i have been duplicating certain business rules and could do with being lifted out and shared between controllers.
From what i've read, the m in asp.net mvc is a layer consisting of entities, viewmodels and services, the latter holding all your shared business logic
now i'm trying to keep things as simple as possible, i don't want to wrap entity framework in some UoW/Repo and use it as-is, it is very unlikely that i'll stop using entity framework in this applications lifetime and i'm not doing unit tests and i'm not that bothered about tight coupling, so i don't feel i need an IoC container, but all the tutorials i've read seems to use either an IoC container or wraps dbcontext/ef in a UoW/Repo.
I've read that there should only be a single instance (which in the tutorials i've seen is managed via an IoC container) of DbContext per httprequest, would this be achieved by instantiating it in the controllers constructor and then passing that reference to any services needed in the controller and then disposing it at the end of the request? is this the correct way of managing dbcontext?
Controller example:
public class SupplierController : Controller
{
private Meerkat3Context context;
private SupplierService supplierService;
private ratingService SupplierRatingService;
public SupplierController()
{
// instantiate the dbcontext
this.context = new Meerkat3Context();
// pass dbcontext into the constructors of my services
this.supplierService = New SupplierService(context);
this.ratingService = New SupplierRatingService(context);
}
public ActionResult Index(Guid id)
{
var supplier = supplierService.getSupplier(id);
// construct viewmodel
return new SupplierIndexViewModel()
{
SupplierId = supplier.Id,
SupplierName = supplier.Name,
SupplierRating = ratingService.getHighestRating(supplier.Id),
NearbySuppliers = supplierService.getNearbySuppliers(supplier.Id),
// etc
};
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
context.Dispose();
}
base.Dispose(disposing);
}
}
Service examples:
public class SupplierService
{
private Meerkat3Context context;
public SupplierService(Meerkat3Context context)
{
this.context = context;
}
public Supplier getSupplier(Guid id)
{
return context.Where(x => x.SupplierId == id)
.FirstOrDefault()
.Select(x => new Supplier()
{
Id = x.Id,
Name = x.Name
// etc
});
}
public Supplier getNearbySuppliers(Guid id)
{
return context.Suppliers.Where(x => context.SupplierAddresses
.Where(y => y.AddressTypeId == AddressTypes.Location)
.Select(z => z.Address.TownCity)
.Contains(x.SupplierAddresses
.Where(y => y.AddressTypeId == AddressTypes.Location)
.FirstOrDefault()
.Address.TownCity)
);
}
}
public class SupplierRatingService
{
private Meerkat3Context context;
public RatingService(Meerkat3Context context)
{
this.context = context;
}
public SupplierRating getHighestRating(Guid id)
{
return context.SupplierRating
.Where(x => x.SupplierId == id)
.OrderBy(x => x.RatingValue)
.FirstOrDefault()
}
}
If you're trying to strip out the repeated code, this should be fairly simple. In VS you can highlight a section of code and use the hotkeys Ctrl+R,Ctrl+M for refactor, or you can do so by using the context menu highlight code section > right-click > Refactor > Extract Method.
If the usage of the repeated code can be replicated for all entities, you can create a static class that houses this common functionality.
public sealed class Utlities
{
public static CommonA() { }
public static CommonB() { }
... etc...
}
And you can call them easily using Utilities.CommonA(). Another way to reduce redundancy is to use ViewModels. Basically create a copy of the entity you want to use as a ViewModel with additional properties required for the View. If the models have data in common, create a base class to inherit those commonalities from.
public class BaseViewModel
{
public Type Prop {get; set;}
public Type Prop2 {get; set;}
...etc...
}
public class SpecificViewModel : BaseViewModel
{
SpecificViewModel(Type Prop, Type Prop2) : base(Prop, Prop2, ...etc...) { }
public Type specificProp {get; set;}
...etc...
}
If I understood your question correctly that is.
If what you want is simply moving out reusable logic then your approach is good enough. But please bear in mind that:
it isn't testable (you can't isolate your dependencies and
You're still duplicating the logic, even if it's simply an object construction logic (e.g., in every controller where you need SupplierService you'll have to instantiate Meerkat3Context as well). That can get quite tedious (and that's where DI comes in handy)
With an IoC container your controller would look like.
public class SupplierController : Controller
{
//the controller doesn't need to create the db context now
//this concern is handled now by the IoC container
private SupplierService supplierService;
private RatingService SupplierRatingService;
public SupplierController(SupplierService supplierService, RatingService ratingService)
{
// we don't have to pass the db context now to services, since we retrieve the services from the IoC container. The IoC container auto-wires the services
this.supplierService = supplierService;
this.ratingService = ratingService;
}
public ActionResult Index(Guid id)
{
var supplier = supplierService.getSupplier(id);
// construct viewmodel
return new SupplierIndexViewModel()
{
SupplierId = supplier.Id,
SupplierName = supplier.Name,
SupplierRating = ratingService.getHighestRating(supplier.Id),
NearbySuppliers = supplierService.getNearbySuppliers(supplier.Id),
// etc
};
}
// the controller doesn't need a dispose method since the IoC container will dispose the dbcontext for us
}
You don't have to follow the Dependency Inversion Principle to use an IoC container, but you can count on a IoC container to create and to manage the lifetime of your services objects.
You configure the IoC container to create a single instance of a dbcontext per a web request. The good part is this is configurable and, if you later decide is better to have a different dbcontext instance per service, then you just change this in a single place and not in every controller and every action method where you use the new keyword.
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.
I have a simple repository that fetches some data using EF6. I'm also using a DI framework to inject the dependencies.
namespace Domain
{
public interface IMyRespository
{
List<MyObject> FetchObjects();
}
}
namespace Data
{
public class MyRepository : IMyRepository
{
private readonly MyDbContext _context;
public MyRepository(MyDbContext context)
{
_context = context;
}
public List<MyObjects> FetchObjects()
{
return _context.MyObjects.ToList();
}
}
}
A new requirement states that I need to log each FetchObjects() call and it's outputs. I thought this would be perfect example to apply the Decorator pattern.
namespace Domain
{
public class MyRepositoryDecorator : IMyRepository
{
private readonly IMyRepository _inner;
private readonly ILogRepository _logRepository;
public MyRepositoryDecorator(IMyRepository inner, ILogRepository logRepository)
{
_inner = inner;
_logRepository = logRepository;
}
public List<MyObjects> FetchObjects()
{
var objects = _inner.FetchObjects();
var logObject = new LogObject(objects);
_logRepository.Insert(logObject);
_logRepository.Save();
return objects;
}
}
}
Now I'm looking to employ the UnitOfWork pattern and I'm unsure how to implement in this case.
As I understand it some component needs to manage the UnitOfWork. So in this case a service class would make some calls and at the end call Save/Commit on the UnitOfWork class.
However if the repository interface indicates a readonly action there is no reason for the service class to wrap the call in a UnitOfWork and call Save/Commit at the end. It would look really weird too. However the decorator requires this to do it's job.
I'm probably missing some essential construct here. Any ideas on how to properly approach this scenario?
It would be a bad idea to mix UoW with Repository using Decorator (or similar) simply because it is not unusual for UoW to span across multiple repositories.
Also it is not up to the Repository to decide whether UoW should be committed or not. Repositories should know as less as possible about UoWs, ideally (and it is the case most of the time) nothing.
In your scenario the UnitOfWork class would pretty much only handles the transaction, so it can be implemented as a simple wrapper around TransactionScope, something like:
public sealed class UnitOfWork : IDisposable {
private readonly TransactionScope _transaction;
public UnitOfWork() { _transaction = new TransactionScope(); }
public void Commit { _transaction.Commit(); }
public void Dispose { _transaction.Dispose(); }
}
Now it is up to the service to instantiate/commit UoW, not up to Repository:
//assuming in a service
public void DoSomething() {
using(var uow = new UnitOfWork()) {
_repositoryA.UpdateSomething();
_repositoryB.DeleteSomething();
_uow.Commit();
}
}
And if your service only wants to read the data, then just do not use UnitOfWork in that operation (or use it without calling Commit so it will just be disposed).
In case if your repository needs to know about UoW, it will normally be passed as another parameter in its behavior method.
Note that it is not done because Repository wants to call Commit, but sometimes (rarely) it is needed for the repository to "enlist" to UoW. These cases are rather more complex.