How Use DependencyInjection in GenericRepository and UnitOfWork - c#

I have a WindowsForm Project With this design :
DAL(GenericRepository => UnitOfWork) => BLL(Service) => UI
And use EntityFramWork, Interface, GenericRepository, Dependency Injection
My Code in Repository(DAL) :
public class Repository : RepositoryBase, IDisposable, IRepository where T : class
{
private readonly DbSet dbSet;
private bool disposed = false;
public Repository(GlobalERPEntities dbContext)
{
DBContext = dbContext;
dbSet = DBContext.Set();
}
public virtual IEnumerable GetAll()
{
return dbSet.ToList();
}
}
UnitOfWork(DAL) :
public class UnitOfWork : RepositoryBase, IUnitOfWork, IDisposable
{
private Dictionaryobject> repositories;
private bool disposed = false;
public UnitOfWork(GlobalERPEntities dbContext)
{
DBContext = dbContext;
}
public IRepository Repository() where T : class
{
if (repositories == null)
{
repositories = new Dictionaryobject>();
}
if (repositories.Keys.Contains(typeof(T)) == true)
{
return repositories[typeof(T)] as Repository;
}
Repository repo = new Repository(DBContext);
repositories.Add(typeof(T), repo);
return repo;
}
Service(BLL) :
public class Service_HR_Person : IService_HR_Person , IDisposable
{
private readonly IUnitOfWork UnitOfWork;
public Service_HR_Person(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
public virtual IEnumerable GetAll()
{
return UnitOfWork.Repository().GetAll().ToList();
}
MyForm(UI) :
using (Service_HR_Person srvPerson = new Service_HR_Person())
{
srvPerson.Delete(base.rowid);
try
{
srvPerson.Save();
MessageManager.Show(Enums.MessageBoxType.InformationTransactionSuccessfully);
}
catch (Exception ex)
{
MessageManager.Show(ErrorManager.ProccessException(ex), Enums.MessageBoxType.Error);
}
}
Iknow should not use DAL Layer in UI layer and BLL is between DAL and UI
but i have error in ui
using (Service_HR_Person srvPerson = new Service_HR_Person())
"new Service_HR_Person()" say need an arguman in () that is unitofwork but we should not use unitofwork in UI
i read some article and sample that use IOC , ninject ,bootstraper and ... but i cant write true code
How To use Ninject or IOC?
please help me with code
thankyou

add a new project to solution with name "Configure"
add castle.windsor from NuGet to all project
add a class to this project with name "Bootstrapper" and write this code
public static WindsorContainer Container = null;
public static void WireUp()
{
Container = new WindsorContainer();
Container.Register(Component.For<GlobalERPEntities>());
Container.Register(Component.For<IUnitOfWork>().ImplementedBy<UnitOfWork>());
Container.Register(Component.For<IService_HR_Person>().ImplementedBy<Service_HR_Person>());
}
and edit your code in UI
using (Service_HR_Person srvPerson = Bootstrapper.Container.Resolve<Service_HR_Person>())
{
srvPerson.Delete(base.rowid);
try
{
srvPerson.Save();
RemoveRow();
MessageManager.Show(Enums.MessageBoxType.InformationTransactionSuccessfully);
}
catch (Exception ex)
{
MessageManager.Show(ErrorManager.ProccessException(ex), Enums.MessageBoxType.Error);
}
}
this line
using (Service_HR_Person srvPerson = Bootstrapper.Container.Resolve<Service_HR_Person>())
and edit Program.cs with this code
static void Main(string[] argss)
{
Bootstrapper.WireUp();
this is work corectly

Related

How to set up .net core service that uses a generic repository

I am building a generic data repository using .netcore 3.0. with EF Core. How can I set up the service where I don't have to provide the actual entity name such as this:
services.AddScoped<RepositoryBase<Feature>>();
Is there a way to configure options that will all me to do this?
These are mostly CRUD operations.
The Generic repository base
namespace CoreAPI1.Data.Services
{
public class RepositoryBase<TEntity> where TEntity : class
{
private readonly DbContext _context;
private readonly DbSet<TEntity> _dbSet;
public RepositoryBase(DbContext context)
{
_context = context;
if (_context == null)
throw new ArgumentNullException();
_dbSet = context.Set<TEntity>();
}
public async Task<IEnumerable<TEntity>> GetAll()
{
return _dbSet.AsNoTracking().ToList();
}
}
}
The services
public static void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TruckContext>(ServiceLifetime.Scoped);
services.AddScoped<IFileService, FileService>();
services.AddScoped<IImageRepository, ImageRepository>();
services.AddScoped<RepositoryBase<Feature>>();
services.AddControllers();
// services.AddAutoMapper(typeof(Truck));
services.AddMvc(_x=>_x.EnableEndpointRouting =
false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
The calling controller
namespace CoreAPI1.Data.Controllers
{
[Route("api/features")]
[ApiController]
public class FeaturesController :ControllerBase
{
private RepositoryBase<Data.Entities.Feature> _repository;
private IMapper _mapper;
public FeaturesController(RepositoryBase<Data.Entities.Feature> repository, IMapper mapper)
{
_repository = repository ?? throw new ArgumentNullException(nameof(_repository));
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
[HttpGet]
public async Task<IEnumerable<Domain.Models.Feature>> GetFeatures()
{
var _features = await _repository.GetAllAsync();
List<Domain.Models.Feature> _returnedFeatures = new List<Domain.Models.Feature>();
try
{
foreach (var f in _features)
{
var _returnedFeature = _mapper.Map<Domain.Models.Feature>(f);
_returnedFeatures.Add(_returnedFeature);
}
return _returnedFeatures;
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
}
}
You can register the type generically, if that's what you're talking about:
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
That would then inject Repository<Foo> for IRespository<Foo>, for example.
Implement Unit of Work class that wraps DbContext and creates repository.

How to register a class to IoC in Prism

I write an application with WPF. I use the Prism library with IoC as Prism.DryIoC.
I have an AppDbContext.cs class to declare the connection string to the database (here is MongoDB)
public class AppDbContext : BaseMongoRepository
{
public AppDbContext(string connectionString, string databaseName = null) : base(connectionString, databaseName)
{
}
}
I have a class MyService.cs that uses the AppDbContext class, I declare in the constructor.
public class MyService : IMyService
{
private AppDbContext _dbContext;
public IdentifierRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public void AddCustomer(Customer model)
{
// Some code....
_dbContext.Add(model);
}
}
In the App.xaml.cs class I override the method
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IAuthenticationService, AuthenticationService>();
// MongoDB
var connectionString = SharedCommon.LocalAppSettings.Database.ConnectionString;
var database = SharedCommon.LocalAppSettings.Database.DatabaseName;
// How to register class MyService.cs here?
// I dont known.
containerRegistry<MyService>(() => new MyService(new AppDbContext(connectionString, database))); // Wrong code
}
You can find all the registration methods here.
For singleton MyService:
var myService = new MyService(new AppDbContext(connectionString, database)));
containerRegistry.RegisterInstance(myService);
For multiple instances you could use a factory instead.
public class MyServiceFactory
{
private readonly AppDbContext appDbContext;
public MyServiceFactory(AppDbContext appDbContext)
{
this.appDbContext = appDbContext;
}
public MyService Create() => new MyService(appDbContext);
}
Register the instance of the factory:
var context = new AppDbContext(connectionString, database);
var factory = new MyServiceFactory(context);
containerRegistry.RegisterInstance(factory);
Then create your service instance:
var factory = container.Resolve<MyServiceFactory>();
var service = factory.Create();

How to setup a C# Generic Base Service Class and use in ASP.Net Core Application

I understand the concept of how to create generic class in C# quit well but what I'm trying to archive is a little bit different from what I've done before.
I use to create Service Management classes and write and all the methods I'll be needing in the controller layer using dependency Injections but i figured that am doing the same thing over and over for all my entities so I wanted to leverage the concept of Generic class which am already using as my Repository in the service layer as well so I'll cut the pain of rewriting the same thing over and over.
So this is what I've done so far, I went ahead and create the a concrete Generic Class
/// <summary>
/// Base Service Generic Class
/// </summary>
/// <typeparam name="TEntity"> Domain Entity</typeparam>
/// <typeparam name="TDataObject"> Data Object</typeparam>
public class BaseServices<TEntity, TDataObject> where TEntity : class, IDataObject, new()
{
public FMDbContext _context;
public IFactoryInit _factory;
public IUnitOfWork _uow;
public BaseServices(IUnitOfWork uow, IFactoryInit factory)
{
_uow = uow;
_factory = factory;
}
private Repository<TEntity> _repository { get; }
private ServiceFactory _serviceFactory { get; }
public Repository<TEntity> Repository
{
get { return _repository ?? new Repository<TEntity>(_context); }
}
public ServiceFactory SFactory
{
get { return _serviceFactory ?? new ServiceFactory(); }
}
public class ServiceFactory : BaseFactory<TEntity, TDataObject>
{
}
public TDataObject GetSingle(Guid id)
{
try
{
TEntity _entity = Repository.GetById(id);
var _obj = SFactory.SingleMappingEntityToObject(_entity);
return _obj;
}
catch (Exception ex)
{
throw ex;
}
}
public IEnumerable<TDataObject> GetMany()
{
try
{
var entities = Repository.Get(null, null, false);
var _objs = SFactory.ListMappingEntitiesToObjects(entities);
return _objs;
}
catch (Exception ex)
{
throw ex;
}
}
public Task<TDataObject> CreateAsync(TDataObject obj)
{
return Task.Run(() =>
{
try
{
var entity = SFactory.SingleMappingObjectToEntity(obj);
entity.Id = IdentityGenerator.NewSequentialGuid();
Repository.Insert(entity: entity);
_context.SaveChangesAsync();
var _resp = SFactory.SingleMappingEntityToObject(entity);
return _resp;
throw new InvalidOperationException("Internal Server Error!");
}
catch (Exception ex)
{
throw ex;
}
});
}}
As you've seen I brought in my IUnitOfWork where am initialising all my repository inside.
And now this is how am calling it on my service
public class ProductService : BaseServices<Product, ProductObject>
{
public ProductService(IUnitOfWork uow, IFactoryInit factory) : base(uow, factory)
{
}
}
Then I went ahead to bring all the servies in one class so I can use .Net Core Dependency Injection to bind it once
public class ServiceInit : IServiceInit
{
private IFactoryInit _factory;
private IUnitOfWork _uow;
private ProductService _productService;
public ProductService ProductServices
{
get { return _productService ?? new ProductService(_uow, _factory); }
}
}
That's all I've done but I keep getting Null Reference Exception in my UnitOfWork initialisation and I even tried this
public IUnitOfWork UnitOfWork
{
get
{
if (_uow == null)
{
_uow = new UnitOfWork(_context);
}
return _uow;
}
}
Explicitly and am still get null reference
But this pattern is still working perfectly well, which is the pattern of creating services repeatedly for all my entity which am very tired of
{
public class VendorManagementServices : IVendorManagementServices
{
private IFactoryInit _factory;
private IUnitOfWork _uow;
public VendorManagementServices(IUnitOfWork uow, IFactoryInit factory)
{
_uow = uow;
_factory = factory;
}
}
So, I dont know what am missing in my BaseService that keeps throwing
System.NullReferenceException: Object reference not set to an instance of an object.
Any Ideas guys?

Call different methods, from different repositories, in same transaction using Unit of work

I am still learning UnitOfWork pattern and I am not comfortable with this yet. I found many examples but nothing is clear enough for my problem.
I want use UnitOfWork with Ado.Net.
I have many repositories. I want call different methods from different repositories in same transaction using Unit of work.
For example a have this 2 repositories.
public class FirstRepository : IFirstRepository
{
private readonly ILogger logger;
private readonly IImportConfiguration configuration;
public FirstRepository(ILogger logger, IImportConfiguration configuration)
{
this.logger = logger;
this.configuration = configuration;
}
public int Save()
{
//Save to DB with Ado.Net
return 1;
}
}
public class SecondRepository : ISecondRepository
{
private readonly ILogger logger;
private readonly IImportConfiguration configuration;
public SecondRepository(ILogger logger, IImportConfiguration configuration)
{
this.logger = logger;
this.configuration = configuration;
}
public int Update()
{
//Update in DB with Ado.Net
return 1;
}
}
I want call functions Save() and Update() in same transaction.
using (var uow = UnitOfWorkFactory.Create())
{
firstRepository.Save();
secondRepository.Update();
_unitOfWork.SaveChanges();
}
Problem is how to use same UnitOfWork in both repositories ? Only thing I can see is add additional parameter to functions
//in first repository
Save(IUnitOfWork uow)
//in second repository
Update(IUnitOfWork uow)
//****************************
using (var uow = UnitOfWorkFactory.Create())
{
firstRepository.Save(uow);
secondRepository.Update(uow);
_unitOfWork.SaveChanges();
}
This is ugly solution, because i must have this parameter in all functions that work with DB.
I am using Dependency injection. ILogger and IImportConfiguration are injected with AutoFac. Maybe would be good to register all repositories in UnitOfWork? But how to do that? I cant have just one instance injected in all repositories.
Any idea?
public class UnitOfWork
{
public DbSet<Company> Companies { get; set; }
public int SaveChanges()
{
underlyingContext.SaveChanges();
}
}
public class UnitOfWorkFactory
{
public UnitOfWork Create()
{
// real creation logic
return new UnitOfWork();
}
}
public class CompanyRepository
{
private readonly UnitOfWork uow;
public CompanyRepository(UnitOfWork uow)
{
uow = uow;
}
public void Add(Company company)
{
uow.Companies.Add(company);
}
}
public class CompanyRepositoryFactory
{
public Create(UnitOfWork uow)
{
new CompanyRepository(uow);
}
}
Tying it all together:
var uow = new UnitOfWorkFactory().Create();
var companyRepository = new CompanyRepositoryFactory().Create(uow);
So to use DI, you need to create interfaces for all these.
The unit of work is based round some Data Layer connection, for example EF uses DbContext which you would use in the underlying UnitOfWork class.
Other things you can do is make IUnitOfWork (the interface) inherit IDisposable so you use the using().
To make it so you don't have a hundred repository classes (although not really a bad thing) you can make it Generic, so IRepository<T> and Repository<T>
So for a generic repo and unit of work using EF.
public class UnitOfWork : IUnitOfWork
{
ProjectDbContext context;
public UnitOfWork() {
context = new ProjectDbContext();
}
public IQueryable<T> Query<T>(Expression<Func<bool, t>> predicate)
{
return context.Set<T>().Where(predicate);
}
public void Add<T>(T entity)
{
context.Set<T>().Add(entity);
}
public int SaveChanges()
{
return context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class UnitOfWorkFactory
{
Lazy<UnitOfWork> lazyUOW = new Lazy<UnitOfWork>(() => new UnitOfWork());
public UnitOfWork Create()
{
// having the DI initialise as Singleton isn't enough.
return lazyUOW.Value;
}
}
public class Repository<T> : IRepository<T>
{
private readonly IUnitOfWork uow;
public Repository(IUnitOfWork uow)
{
uow = uow;
}
public void Add(T entity)
{
uow.Add(entity);
}
public List<T> AllBySomePredicate(Expression<Func<bool, T>> predicate)
{
return uow.Query(predicate).ToList();
}
}
public class RepositoryFactory : IRepositoryFactory
{
public Create<T>(UnitOfWork uow)
{
new Repistory<T>(uow);
}
}
Usage:
public class CompanyController : Controller
{
private readonly IUnitOfWorkFactory uowFactory;
private readonly IRepositoryFactory repoFactory;
public CompanyController (
IUnitOfWorkFactory uowFactory,
IRepositoryFactory repoFactory)
{
uowFactory = uowFactory;
repoFactory = repoFactory;
}
public ActionResult Index()
{
using(var uow = uowFactory.Create())
{
var companyRepo = repoFactory.Create<Company>(uow);
return View(companyRepo.AllBySomePredicate(x => x.CompanyJoined == DateTime.Now.AddMonths(-2)));
}
}
}

Cordinate between my repository classes and controller classes to be using the same Context object

I am working on an asp.net mvc web application. now i have created multiple repositories classes, for example i have the following abstract repository classes:-
public interface ISkillRepository : IDisposable
{//code goes here..
&
public interface IStaffRepository : IDisposable
{//code goes here
and the model Repositories:-
public class SkillRepository : ISkillRepository , IDisposable
{
private SkillManagementEntities context = new SkillManagementEntities();
//code goes here
&
public class StaffRepository : IStaffRepository , IDisposable
{
private SkillManagementEntities context = new SkillManagementEntities();
now inside y controller i am intializing and creating the repo as follow:-
public class SkillController : Controller
{
private ISkillRepository skillRepository;
public SkillController() : this(new SkillRepository()) {}
public SkillController(ISkillRepository repository)
{
skillRepository = repository;
}
but currently i got the following error inside my application:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
and the problem is that i need to be passing the same context accross the repos and controllers. so can anyone adivce on this:-
how i can inside one model repo to reference another repo using the same context class. for example inside the Staff repositoryto referecne the skill repository?
how i can inside a controller class to refer multiple repos , but at the same time pass the same context object among them , so if i issue a save() it will wrap all the statements inside one transaction. for example insie my skillController to reference both the skill & staff repos using the same context object ?
Thanks
Edit
I have created the following Unit of work class:-
public class UnitOfWork : IDisposable
{
private SkillManagementEntities context = new SkillManagementEntities();
private SkillRepository skillRepository;
private StaffRepository staffRepository;
private SecurityRoleRepository securityroleRepository;
public SkillRepository SkillRepository
{
get
{
if (this.skillRepository == null)
{
this.skillRepository = new SkillRepository(context);
}
return skillRepository;
}
}
public StaffRepository StaffRepository
{
get
{
if (this.staffRepository == null)
{
this.staffRepository = new StaffRepository(context);
}
return staffRepository;
}
}
public SecurityRoleRepository SecurityRoleRepository
{
get
{
if (this.staffRepository == null)
{
this.staffRepository = new SecurityRoleRepository(context);
}
return securityroleRepository;
}
}
public async Task Save()
{
await context.SaveChangesAsync();
}
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);
}
}
}
and then inside my repo i did the following:-
public class SecurityRoleRepository : ISecurityRoleRepository , IDisposable
{
private SkillManagementEntities context;// = new SkillManagementEntities();
public SecurityRoleRepository(SkillManagementEntities context)
{
this.context = context;
and on the controller class i will be referencing the UnitOfWork as follow:-
public class SecurityRoleController : Controller
{
private UnitOfWork unitOfWork = new UnitOfWork();
public async Task<ActionResult> Index(string filter = null, int page = 1, int pageSize = 20, string sort = "Name", string sortdir = "ASC")
{
try
{
var records = new PagedList<SecurityRole>();
ViewBag.filter = filter;
records.Content = await unitOfWork.SecurityRoleRepository.GetSecurityRoleForGrid(filter, page, pageSize, sort, sortdir).ToListAsync();
now i am facing a problem is that how i can referecne a repo from another Repo ? for example how i can reference the Skill repo inside the SecurityRole repo ?
EDIT Final
i did the following steps:-
1. i install
Install-Package Ninject.MVC5
2. then i created the following dependency class:-
public class YourDependencyResolverClass : IDependencyResolver
{
private IKernel kernel;
public YourDependencyResolverClass()
{
kernel = new StandardKernel();
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
kernel.Bind<ISkillRepository>().To<SkillRepository>();
kernel.Bind<IStaffRepository>().To<StaffRepository>();
kernel.Bind<ISecurityRoleRepository>().To<SecurityRoleRepository>();
kernel.Bind<ICustomerRepository>().To<CustomerRepository>();
kernel.Bind<ISkillVersionHistoryRepository>().To<SkillVersionHistoryRepository>();
}
}
}
3.now inside my SkillRepository class i will be referencing the StaffRepository as follow:-
public class SkillRepository : ISkillRepository , IDisposable
{
private SkillManagementEntities context ;
private IStaffRepository staffrepo = (IStaffRepository)DependencyResolver.Current.GetService(typeof(IStaffRepository));
public SkillRepository(SkillManagementEntities context)
{
this.context = context;
}
Finally inside my action method i will be calling the Uiteofwork class as follow:-
public class StaffController : Controller
{
//private SkillManagementEntities db = new SkillManagementEntities();
UnitOfWork unitofwork = new UnitOfWork();
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term).Select(a => new { label = a.SamAccUserName }).ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
and the unite of work class is :-
public class UnitOfWork : IDisposable
{
private SkillManagementEntities context = new SkillManagementEntities();
private SkillRepository skillRepository;
private StaffRepository staffRepository;
private SecurityRoleRepository securityroleRepository;
private CustomerRepository customerRepository;
private SkillVersionHistoryRepository SVH;
public SkillRepository SkillRepository
{
get
{
if (this.skillRepository == null)
{
this.skillRepository = new SkillRepository(context);
}
return skillRepository;
}
}
public StaffRepository StaffRepository
{
get
{
if (this.staffRepository == null)
{
this.staffRepository = new StaffRepository(context);
}
return staffRepository;
}
}
public CustomerRepository CustomerRepository
{
get
{
if (this.customerRepository == null)
{
this.customerRepository = new CustomerRepository(context);
}
return customerRepository;
}
}
public SecurityRoleRepository SecurityRoleRepository
{
get
{
if (this.securityroleRepository == null)
{
this.securityroleRepository = new SecurityRoleRepository(context);
}
return securityroleRepository;
}
}
public SkillVersionHistoryRepository SkillVersionHistoryRepository
{
get
{
if (this.SVH == null)
{
this.SVH = new SkillVersionHistoryRepository(context);
}
return SVH;
}
}
public async Task Save()
{
await context.SaveChangesAsync();
}
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);
}
}
So can you adivce if my approach of using unitefwork and DI will guarantee that all my statements will be warped inside a single DB transaction ? thnaks?
We handle this by sharing a context using a singleton that is scoped to the request using HttpContext:
public MyContext GetContext()
{
if (System.Web.HttpContext.Current.Items["MyScopedContext"] == null)
{
System.Web.HttpContext.Current.Items["MyScopedContext"] = new MyContext();
}
return (MyContext)System.Web.HttpContext.Current.Items["MyScopedContext"];
}
The context object (repository) itself essentially houses a Unit of Work. The code I added above just gives you a way to share a single repository across all code running within a request. If your repository classes are defined in the scope of a web application, you can just replace your direct instantiation of SkillManagementEntities() with a call to a GetContext() method.
On the other hand if your repositories are defined in a layer shared by heterogeneous applications, you may need to get your context from a factory object that you can inject as needed. Either way, creating a new context object per repository is what's causing your issue.
Not an answer: this "use DI" suggestion answers a bit different question - OP is looking for "unit-of-work" pattern - while basic case (lifetime of unit of work matches lifetime of request/controller) can easily be solved with any DI framework, managing multiple units of work or units of work with longer lifetime is much harder and dedicated "unit of work factory" (sample usage) is likely the solution.
Usually when you go that far with interfaces/repositories and constructor dependency injection you have some Dependency Injection framework. There is a good chance that one you are using already provides "per HTTP request" resolution or allows to easily add one.
I.e. if you using Unity there is PerRequestLifetime lifetime manager that makes all .Resolve calls for the same interface/object to return the same instance for given request. See more info in DI with Unity MSDN article.
Approximate sample:
container.RegisterType<ISkillRepository, SkillRepository>();
container.RegisterType<IOtherRepository, OtherRepository>();
container.RegisterType<TheContext, TheContext>(new PerRequestLifetime());
With such registration and assuming you've configured ASP.Net MVC to use Unity to resolve types when controller is created it will get necessary dependencies (new instances as registered with default lifetime), but both will share the same context (assuming each depends on TheContext class either via constructor or property injection).

Categories

Resources