Generic Service Implementation - asp.net-mvc

In my learning ASP.NET MVC 4 application, I use repository pattern and service layers. Entity framework and Autofac is used in the project. My data classes are simple and almost all operations are basic CRUD operations.
I have an abstract repository base as:
public abstract class RepositoryBase<T> where T : class
And this is a sample repository for the entity Sample1:
public class Sample1Repository : RepositoryBase<Sample1>, ISample1Repository
{
public Sample1Repository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
}
}
public interface ISample1Repository : IRepository<Sample1>
{
}
This is my controller:
public class SampleController : Controller
{
private readonly ISampleService _sampleService;
public SampleController(ISampleService sampleService)
{
this._sampleService = sampleService;
}
}
And, lastly this is my service:
public interface ISampleService
{
IEnumerable<Sample1> GetSample1s();
Sample1 GetSample1(int id);
void CreateSample1(Sample1 item);
void DeleteSample1(int id);
void SaveSample1();
}
public class SampleService : ISampleService
{
private readonly ISample1Repository _sample1Repository;
private readonly IUnitOfWork _unitOfWork;
public SampleService(ISample1Repository sample1Repository, IUnitOfWork unitOfWork)
{
this._sample1Repository = sample1Repository;
this._unitOfWork = unitOfWork;
}
}
Now, I have these questions:
1) Do I need to create a separate class for each entity repository. (ie. another Sample2Repository for the entity Sample2)
2) Can I use a generic service for doing those CRUD tasks?
3) If generic service is possible. How can I register it/them in Autofac bootstrapper?

1) Do I need to create a separate class for each entity repository.
If you can, create a single generic IRepository<T> implementation and map that to this open generic interface.
2) Can I use a generic service for doing those CRUD tasks?
Of course you can, but the real question is: is it useful to do so? Seems to me that your ISampleService simply duplicates the logic from the IRepository<T>. It probably forwards to this repository. Seems like a useless abstraction to me. If your application is truly CRUD, you can inject your repository directly into your controller.
3) If generic service is possible. How can I register it/them in
Autofac bootstrapper?
You can map an open-generic interface to an open generic implementation as follows:
builder.RegisterGeneric(typeof(EntityFrameworkRepository<>))
.As(typeof(IRepository<>))
If you have many concrete (non-generic) IRepository<T> implementations and want to batch-register them, you can do this as follows:
builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly)
.AsClosedTypesOf(typeof(IRepository<>));

Related

Resolve all already created service instances from .NET service provider

I would like to request all created instances from a transient service via the IServiceProvdier. My problem is that requesting them seems to create additional instances instead of retrieving only the already existing instances.
I have a service interface and implementation
public interface ISomeService {}
public class SomeService : ISomeService
{
public SomeService()
{
}
}
It is registered transient
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ISomeService, SomeService>();
}
Another service where I try to get all already created services
public class AnotherService
{
// calls the constructor of SomeService
//public AnotherService(IEnumerable<ISomeService> instances) {}
public AnotherService(IServiceProvider serviceProvider)
{
// calls the constructor of SomeService
//IEnumerable<ISomeService> instances = serviceProvider.GetServices<ISomeService>();
// calls the constructor of SomeService
//IEnumerable<ISomeService> instances = serviceProvider.GetRequiredServices<ISomeService>();
}
}
I don't know why the constructor of SomeService is called but it definitly seems to do it due to the calls of Get...
Anyone managed to get the list of instances without creating one?
By definition a transient service will always be created each time you request the service provider or the DI system to resolve it.
If you want to reuse the same instances you can register services with a different lifetime
services.AddSingleton<ISomeService, SomeService>();
or
services.AddScoped<ISomeService, SomeService>();
if you register the dependency as a singleton than there will be a single instance of there service for the entire application lifetime.
if you register the dependency with the scoped lifetime than a new instance will be created for each scope. In Asp.Net a scope consists of a request.
If you want your dependency to be transient and want to have track of all the instances that have been created you can do a little trick using static references:
public static class SomeServiceReferences {
public static readonly IList<ISomeService> References { get; } = new List<ISomeService>();
}
public class SomeService: ISomeService {
public SomeService() {
SsomeServiceReferences.References.Add(this);
}
}
but I don't reccomend this approach cause holding the reference of those dependencies might cause performance problems and if you need to do such a thing there might be some problems with the design of your application.

Injecting Different Implementations of Same Interface in ASP.NET 5

In ASP.NET 5, I have an IRepository interface that I used to access some databases, like this:
public interface IRepository {
IQueryable<T> QueryItems(string sql);
}
public class Repository : IRepository {
private readonly string ConnectionString;
public Repository(string connStr) {
// Save the injected connection string
this.ConnectionString = connStr;
}
public IQueryable<T> QueryItems(string sql) {
// Implementation ignored here
}
}
In my Startup.cs class, I am registering the IoC/DI like this:
services.AddTransient<IRepository>(s => new Repository("DUMMY_CONNSTR"));
That all works fine if I only have one connection string. However, how can I register and subsequently inject the correct IRepository if I use the Repository to connect to 2+ different databases with different connection strings?
services.AddTransient<IRepository>(s => new Repository("DUMMY_CONNSTR"));
services.AddTransient<IRepository>(s => new Repository("DIFFERENT_CONNSTR"));
In older IoC/DI systems, I would have use "named" implementations that could be resolved with something like a [Dependency("DUMMY")] attribute on the constructor parameter.
Any help would be appreciated.
There are a few approach that you can take one is to inject a factory and base on the specific criteria you can produce a repository, the other approach is use a Dispatcher that also produce the repository base on the criteria, below is a question that I ask with the same problem. The question below have both approach but they were codding a beta version of .net core
See this question for reference and code
You can substitute StructureMap or Autofac for the default DI container (see my blog post for detailed instructions). Both support "named" interface registration (StructureMap named instances and Autofac named and keyed services).
Additionally, if you target dnx451, you can use Autofac's WithKey attribute. Using the Visual Studio sample project from the blog post, add the following dependency in project.json:
"frameworks": {
"dnx451": {
"dependencies": {
"Autofac.Extras.AttributeMetadata": "4.0.0"
}
}
},
Given a test class with the following constructor:
public MyClass([WithKey("logging")] IRepository repository)
{
Repository = repository;
}
you would register everything in ConfigureServices (note the use of WithAttributeFilter():
containerBuilder.Register(c => new Repository("DEFAULT_CONNSTR")).Keyed<IRepository>("default");
containerBuilder.Register(c => new Repository("LOGGING_CONNSTR")).Keyed<IRepository>("logging");
containerBuilder.RegisterType<MyClass>().WithAttributeFilter();

Unit of work + repository + service layer with dependency injection

I am designing a web application and a windows service and want to use the unit of work + repository layer in conjunction with a service layer, and I am having some trouble putting it all together so that the client apps control the transaction of data with the unit of work.
The unit of work has a collection of all repositories enrolled in the transaction along with commit and rollback operations
public interface IUnitOfWork : IDisposable
{
IRepository<T> Repository<T>() where T : class;
void Commit();
void Rollback();
}
The generic repository has operations that will be performed on the data layer for a particular model (table)
public interface IRepository<T> where T : class
{
IEnumerable<T> Get(Expression<Func<T, bool>> filter = null, IList<Expression<Func<T, object>>> includedProperties = null, IList<ISortCriteria<T>> sortCriterias = null);
PaginatedList<T> GetPaged(Expression<Func<T, bool>> filter = null, IList<Expression<Func<T, object>>> includedProperties = null, PagingOptions<T> pagingOptions = null);
T Find(Expression<Func<T, bool>> filter, IList<Expression<Func<T, object>>> includedProperties = null);
void Add(T t);
void Remove(T t);
void Remove(Expression<Func<T, bool>> filter);
}
The concrete implementation of the unit of work uses entity framework under the hood (DbContext) to save the changes to the database, and a new instance of the DbContext class is created per unit of work
public class UnitOfWork : IUnitOfWork
{
private IDictionary<Type, object> _repositories;
private DataContext _dbContext;
private bool _disposed;
public UnitOfWork()
{
_repositories = new Dictionary<Type, object>();
_dbContext = new DataContext();
_disposed = false;
}
The repositories in the unit of work are created upon access if they don't exist in the current unit of work instance. The repository takes the DbContext as a constructor parameter so it can effectively work in the current unit of work
public class Repository<T> : IRepository<T> where T : class
{
private readonly DataContext _dbContext;
private readonly DbSet<T> _dbSet;
#region Ctor
public Repository(DataContext dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
}
#endregion
I also have a service classes that encapsulate business workflow logic and take their dependencies in the constructor.
public class PortfolioRequestService : IPortfolioRequestService
{
private IUnitOfWork _unitOfWork;
private IPortfolioRequestFileParser _fileParser;
private IConfigurationService _configurationService;
private IDocumentStorageService _documentStorageService;
#region Private Constants
private const string PORTFOLIO_REQUEST_VALID_FILE_TYPES = "PortfolioRequestValidFileTypes";
#endregion
#region Ctors
public PortfolioRequestService(IUnitOfWork unitOfWork, IPortfolioRequestFileParser fileParser, IConfigurationService configurationService, IDocumentStorageService documentStorageService)
{
if (unitOfWork == null)
{
throw new ArgumentNullException("unitOfWork");
}
if (fileParser == null)
{
throw new ArgumentNullException("fileParser");
}
if (configurationService == null)
{
throw new ArgumentNullException("configurationService");
}
if (documentStorageService == null)
{
throw new ArgumentNullException("configurationService");
}
_unitOfWork = unitOfWork;
_fileParser = fileParser;
_configurationService = configurationService;
_documentStorageService = documentStorageService;
}
#endregion
The web application is an ASP.NET MVC app, the controller gets its dependencies injected
in the constructor as well. In this case the unit of work and service class are injected. The action performs an operation exposed by the service, such as creating a record in the repository and saving a file to a file server using a DocumentStorageService, and then the unit of work is committed in the controller action.
public class PortfolioRequestCollectionController : BaseController
{
IUnitOfWork _unitOfWork;
IPortfolioRequestService _portfolioRequestService;
IUserService _userService;
#region Ctors
public PortfolioRequestCollectionController(IUnitOfWork unitOfWork, IPortfolioRequestService portfolioRequestService, IUserService userService)
{
_unitOfWork = unitOfWork;
_portfolioRequestService = portfolioRequestService;
_userService = userService;
}
#endregion
[HttpPost]
[ValidateAntiForgeryToken]
[HasPermissionAttribute(PermissionId.ManagePortfolioRequest)]
public ActionResult Create(CreateViewModel viewModel)
{
if (ModelState.IsValid)
{
// validate file exists
if (viewModel.File != null && viewModel.File.ContentLength > 0)
{
// TODO: ggomez - also add to CreatePortfolioRequestCollection method
// see if file upload input control can be restricted to excel and csv
// add additional info below control
if (_portfolioRequestService.ValidatePortfolioRequestFileType(viewModel.File.FileName))
{
try
{
// create new PortfolioRequestCollection instance
_portfolioRequestService.CreatePortfolioRequestCollection(viewModel.File.FileName, viewModel.File.InputStream, viewModel.ReasonId, PortfolioRequestCollectionSourceId.InternalWebsiteUpload, viewModel.ReviewAllRequestsBeforeRelease, _userService.GetUserName());
_unitOfWork.Commit();
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
return View(viewModel);
}
return RedirectToAction("Index", null, null, "The portfolio construction request was successfully submitted!", null);
}
else
{
ModelState.AddModelError("File", "Only Excel and CSV formats are allowed");
}
}
else
{
ModelState.AddModelError("File", "A file with portfolio construction requests is required");
}
}
IEnumerable<PortfolioRequestCollectionReason> portfolioRequestCollectionReasons = _unitOfWork.Repository<PortfolioRequestCollectionReason>().Get();
viewModel.Init(portfolioRequestCollectionReasons);
return View(viewModel);
}
On the web application I am using Unity DI container to inject the same instance of the unit of work per http request to all callers, so the controller class gets a new instance and then the service class that uses the unit of work gets the same instance as the controller. This way the service adds some records to the repository which is enrolled in a unit of work and can be committed by the client code in the controller.
One question regarding the code and architecture described above. How can I get rid of the unit of work dependency at the service classes? Ideally I don't want the service class to have an instance of the unit of work because I don't want the service to commit the transaction, I just would like the service to have a reference to the repository it needs to work with, and let the controller (client code) commit the operation when it see fits.
On to the windows service application, I would like to be able to get a set of records with a single unit of work, say all records in pending status. Then I would like to loop through all those records and query the database to get each one individually and then check the status for each one during each loop because the status might have changed from the time I queried all to the time I want to operate on a single one. The problem I have right now is that my current architecture doesn't allow me to have multiple unit of works for the same instance of the service.
public class ProcessPortfolioRequestsJob : JobBase
{
IPortfolioRequestService _portfolioRequestService;
public ProcessPortfolioRequestsJob(IPortfolioRequestService portfolioRequestService)
{
_portfolioRequestService = portfolioRequestService;
}
The Job class above takes a service in the constructor as a dependency and again is resolved by Unity. The service instance that gets resolved and injected depends on a unit of work. I would like to perform two get operations on the service class but because I am operating under the same instance of unit of work, I can't achieve that.
For all of you gurus out there, do you have any suggestions on how I can re-architect my application, unit of work + repository + service classes to achieve the goals above?
I intended to use the unit of work + repository patterns to enable testability on my service classes, but I am open to other design patterns that will make my code maintainable and testable at the same time while keeping separation of concerns.
Update 1
Adding the DataContext class that inheris from EF's DbContext where I declared my EF DbSets and configurations.
public class DataContext : DbContext
{
public DataContext()
: base("name=ArchSample")
{
Database.SetInitializer<DataContext>(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
base.Configuration.ProxyCreationEnabled = false;
}
public DbSet<PortfolioRequestCollection> PortfolioRequestCollections { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new PortfolioRequestCollectionConfiguration());
base.OnModelCreating(modelBuilder);
}
}
If your purpose for using Unit of Work (UoW) was for testability, you took the wrong path. Unit of work does nothing for testability. Its main purposes is to provide atomic transactions to disparate data sources, provide UoW functionality to a data layer that doesn't already provide it, or to wrap an existing UoW in a way that makes it more easily replaceable... something which you've nullified by using the generic repository (this tightly couples it to Entity Framework anyways).
I suggest you get rid of the Unit of Work completely. Entity Framework is already a UoW. Even Microsoft has changed their mind and no longer recommend UoW with EF.
So, if you get rid of UoW, then you can just use repositories to wrap your EF queries. I don't suggest using a generic repository, as this leaks your data layer implementation all over your code (something your UoW was already doing), but rather create Concrete repoTsitories (these can use generic repositories internally if you like, but the generic repository should not leak outside of your repository).
This means your service layer takes the specific concrete repository it needs. For instance, IPortfolioRepository. Then you have a PortfolioRepository class that inherits from IPortfolioRepository which takes your EF DbContext as a parameter that gets injected by your Depndency Injection (DI) framework. If you configure your DI container to instance your EF context on a "PerRequest" basis, then you can pass the same instance to all your repositories. You can have a Commit method on your repository that calls SavesChanges, but it will save changes to all changes, not just to that repository.
As far as Testability goes, you have two choices. You can either mock the concrete repositories, or you can use the built-in mocking capabilities of EF6.
I have been through that hell hole myself and here's what I have done:
Ditch the UoW completely. EF's DBContext is a UoW basically. No point in re-inventing the wheel.
Per MSDN:
DbContext Class
Represents a combination of the Unit-Of-Work and Repository patterns
and enables you to query a database and group together changes that
will then be written back to the store as a unit.
Service layer + Repo layer seemed like a good choice. However, repos are always a leaky abstraction and espcially when DBContext's DbSet are the equivalent of repositories.
Then when the need for a Windows service arises, things become muddied further with another layer now. Throw async or background processing in the mix, and things quickly start leaking.
If you ask my 2 cents, I would say go with the service layer + EF, one wrapping business logic, the other one wrapping UOW/Repository pattern.
Alternatively, and for Windows Services especially, I'm finding that moving to a command-query based approach works better.
Not only it helps testability, it also helps in asynchronous tasks where I don't have to worry about keeping the DBContext alive even after the request has ended (DBContext is now tied with the command handler and stays alive as long as the async command stays alive).
Now if you've recently ended up digesting all those facts about UOW/Repository pattern, then surely, just even reading about Command-Query pattern will make your mind hurt. I have been down that path but trust me, its worth the time to at least look into it and giving it a try.
These posts may help:
Meanwhile... on the query side of my architecture
Meanwhile... on the command side of my architecture
If you're brave enough (after digesting thru CQRS), then take a look at MediatR which implements the Mediator pattern (which basically wraps up command-query with notifications) and allows to work via pub-sub. The pub-sub model suits nicely in the Windows Service and services layer.

repository pattern in asp. net mvc3

I have recently started teaching myself C# and Asp.net. I am trying to build a simple blog application. I am confused about repository pattern usage. I have seen few tutorials and the implementation varies.
For my blog application, I have two database tables (models) - blogs and comments. Currently, I have a IDbContext which looks like this:
public interface IDBContext
{
IQueryable<Blog> FindAllBlogs();
IQueryable<Blog> FindBlogsInMonth(int month);
Blog GetBlog(int id);
void Add(Blog blog);
void Update(Blog blog);
void Delete(Blog blog);
void Add(Comment comment);
//void Remove(Comment comment);
}
and I have repository which looks like this:
public class BlogRepository : IDBContext
{
private BlogDb db = new BlogDb();
public IQueryable<Blog> FindAllBlogs()
{
return db.Blogs.OrderByDescending(b => b.PublishDate);
}
public Blog GetBlog(int id)
{
return db.Blogs.Single(b => b.BlogID == id);
}
...
}
The other implementation of repository pattern is something like this:
public interface IDbContext
{
IQueryable<Blog> Blogs { get; }
IQueryable<Comments> Comments { get; }
int SaveChanges();
T Attach<T>(T entity) where T : class;
T Add<T>(T entity) where T : class;
T Delete<T>(T entity) where T : class;
}
which calls a repository and there is separate class for queries.
What is the best method to do it?
The easiest method is to use Entity Framework directly, particularly the new DbContext functionality that showed up in Entity Framework 4.1 and later.
The context will contain DbSet properties - each is an implementation of the repository pattern that accomplishes all of the goals you described above. IDbSet can be used if unit testing support is required.
I've seen a lot of demos for the ASP.NET MVC repository patterns online that end up wrapping Entity Framework with a custom repository. It's a waste of time - it's code that wraps other code and doesn't serve any direct purpose aside from adding needless complexity.

Multiple IUnitOfWork implementations in single ASP.NET MVC project

We have a site using Unity and IUnitOfWork for our EF context. Until now we've only been using a single EF Context so this is the one mapped in Unity config. This has all been handled through constructor injection and this is something we'd like to maintain for consistency.
We've now introduced another EF Context for our PaymentController that is used within the site but Unity config currently only allows us to create one type for IUnitOfWork.
I know that I can create a new <register/> element for the new context with a distinct name attribute but how do I implement this within the controller constructor to use the one named payments?
<register type="IUnitOfWork" mapTo="FirstContext" />
<register type="IUnitOfWork" mapTo="PaymentsContext" name="payments"/>
public class PaymentController()
{
public PaymentController(IUnitOfWork unitOfWork)
{
//How to I tell unity that this needs to be a payments
_unitOfWork = unitOfWork;
}
}
Many Thanks
When the FirstContext and PaymentsContext have each an unique set of entities (for instance, each connect to a different database) it is worth wild to explicitly define this in code. One way of doing this is by specifying a factory for each unit of work:
public interface IFirstContextFactory
{
IUnitOfWork CreateNew();
}
public interface IPaymentContextFactory
{
IUnitOfWork CreateNew();
}
public class PaymentController()
{
public PaymentController(PaymentContextFactory paymentContextFactory)
{
//How to I tell unity that this needs to be a payments
this.paymentContextFactory = paymentContextFactory;
}
public void DoSomething()
{
using (var context = this.paymentContextFactory.CreateNew())
{
// Do something useful
context.Commit();
}
}
}
Not only makes this your dependencies very clear (because you know what type of context the code is dealing with), but it also simplifies the DI configuration, because you won't need any named registrations.

Resources