I'm trying to implement a Generic Repository. This is what I've got so far ...
public interface IRepositoryFactory
{
IRepository<T> RepositoryOf<T>() where T : class;
}
public class EntityFrameworkRepositoryFactory : IRepositoryFactory
{
private readonly IWindsorContainer _container;
public EntityFrameworkRepositoryFactory(IWindsorContainer container)
{
_container = container;
}
public IRepository<T> RepositoryOf<T>() where T : class
{
var repository = _container.Resolve<IRepository<T>>();
return repository;
}
}
The RepositoryFactory is used by my unit of work implementation
public interface IUnitOfWork : IDisposable
{
IRepository<T> RepositoryOf<T>() where T : class;
void Commit();
}
Anyway, the question I want to ask is whether having the RepositoryFactory implementation depend on IWindsorContainer is correct?
I needed a way of asking for an IRepository of any type, so my installer code does this ...
// Windsor Container
container.Register(
Component.For<IWindsorContainer>()
.Named("Container")
.Instance(container)
);
Which just seems to go against the whole concept of IoC, but then maybe the whole idea of asking for a repository does that anyway.
Edit (As reply to miensol's answer)
I am already using Windsor to create the repositories for me with the following code in my installer ...
// Generic Repository
container.Register(
Component.For(typeof (IRepository<>))
.ImplementedBy(typeof (EntityFrameworkRepository<>))
.ServiceOverrides(
ServiceOverride.ForKey("objectContext").Eq("ObjectContext"))
);
I have used ServiceLocator in the past to achieve what I want, but have read that it's a bit of an anti-pattern. So was trying to avoid using it. Although I have to admit that I'm not sure why, as what I've done also seems wrong as I am bound to using Castle Windsor as my IoC/DI framework. Service Locator is meant to be framework agnostic.
So, I'm a bit confused!
I'm not entirely sure why do you need IRepositoryFactory when you are using an IoC framework. However having dependencies to specific IoC container implementations scattered though the code base is generally not a good idea. Most of the time when I really can't find a way to make the container inject dependencies to my objects I use Service Locator Pattern, here you can find a commonly used implementation for .net. Then your factory method would look like this:
public IRepository<T> RepositoryOf<T>() where T : class
{
return ServiceLocator.Current.GetInstance<IRepository<T>>();
}
Nevertheless it seems like you could just make Windsor create the generic repository for you anyways:
container.Register(
Component.For(typeof(IRepository<>)).ImplementedBy(typeof(GenericRepositoryImplementation<>))
);
and having them injected to your objects like so:
public class ClassThatRequiresSomeRepos
{
IRepository<OneEntity> repoOne;
IRepository<TwoEntity> repoTwo;
public ClassThatRequiresSomeRepos(IRepository<OneEntity> oneEntityRepository, IRepository<TwoEntity> twoEntityRepository)
{
_repoOne = oneEntityRepository;
_repoTwo = twoEntityRepository;
}
}
Related
I would like to prevent other developers from deviating from the application's architecture by limiting the classes in which the UnitOfWork class can be injected. Or at least make it more obvious that they're deviating from the accepted pattern.
We have a collection of services that all extend the abstract class of BaseService. The BaseService class contains the property for the UnitOfWork class which is injected via dependency injection.
public abstract class BaseService
{
protected readonly IUnitOfWork UnitOfWork;
protected BaseService(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
}
This means if a class needs the UnitOfWork it'll need to extend the BaseService class, but nothing actually prevents a developer from just injecting the UnitOfWork into some other class that's not a service. If they did this, they could potentially be saving changes outside of the service, which is what we're trying to avoid.
Is there a way that we can throw a build error or warning based on the UnitOfWork being injected in some other class?
Two possible solutions come into my mind: One is based on using DI framework features to make the registration only visible in a specific scope of the code. The other one is based on using a public and an internal interface, while the implementation is only registered for the internal interface.
Solution based on DI framework
I best know Autofac, so I name the solution for this DI framework here. But I think other DI frameworks have similar features, so a bit of searching could give you the corresponding feature in your DI framework:
In case that your dependency injection framework is Autofac you can work with lifetime scopes to make specific registrations only available in a limited "area" (scope) of your code. (See also at the official Autofac documentation for an explaination about the concept of liftime scopes: https://autofac.readthedocs.io/en/latest/lifetime/index.html)
Solution via splitting the interface
This approach is to split IUnitOfWork into two interfaces - one which is public and one which is internal and therefore not accessible from other projects. The implementation is only registered for the internal interface, so that other projects cannot inject anything, as the interface is not known to them.
public interface IUnitOfWork
{
// ...
}
internal interface IInjectableUnitOfWork : IUnitOfWork
{
// no content
}
public abstract class BaseService
{
protected readonly IUnitOfWork UnitOfWork;
protected BaseService(IInjectableUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork; // hint: The assignment works, because IInjectableUnitOfWork inherits from IUnitOfWork.
}
}
I am starting to work with DI/IoC and I have some troubles understanding all the concepts.
I have chosen Autofac because it seems it's one of the few that supports both .Net 4.6+ and .Net Core. It seems it also most widely used.
1) Constructor injection - for e.g. in Controllers or my WCF services
I understand that it is impossible to do constructor injection to an object that I am instantiating in my code, meaning it is not automatically instantiated.
2) Property injection
I would like to do something similar to how you do it in Ninject:
[Inject]
public IWeapon Weapon { get; set; }
And as I understund, in Autofac. it is equivelanet to:
builder.RegisterType<Weapon>().As<IWeapon>().PropertiesAutowired();
1. Now, why is the constructor injection the preferred way?
For example, I have:
Factory for repositories
Factory for business engines
Those factories, are just one-liners that should do something like (from another IoC):
public class DataRepositoryFactory : IDataRepositoryFactory
{
T IDataRepositoryFactory.GetDataRepository<T>()
{
return ObjectBase.Container.GetExportedValue<T>();
}
}
Some methods require both, some do not. Doing something like:
public SampleControllerOrManager(IUnitOfWork unitOfWork, IRepositoryFactory repositoryFactory, IBusinessEngineFactory engineFactory)
seems like a waste of resources.
I understand that this helps with testing (?).
But this looks cleaner:
public SampleControllerOrManager(IUnitOfWork unitOfWork)
[Inject]
public IRepositoryFactory RepositoryFactory { get; set; }
[Inject]
public IBusinessEngineFactory EngineFactory { get; set; }
2. Injecting Entity Framework DbContext into the repositories
I want to register the context with the Container and have that injected into the object constructors of the UnitOfWork and the Repository's. I want to be sure the same instance is injected into all the objects. How do I do it in Autofac?
public class Repository : IRepository {
//context injected here
public Repository (DbContext context){ ... }
}
public class Manager {
public void SomeMethod(){
IRepository = RepositoryFactoryGetDataRepository<ISomeTypeRepository>
}
}
Constructor Injection
Constructor injection is the preferred way because it makes them obvious. You can't instantiate the class if you do not provide the required dependencies.
With property injection dependencies are hidden and you could instantiate the class with some missing injections which could lead you to believe that the class is fully initialized and ready to be used. Eventually, you could get an error if you try use a functionality that needs a missing dependency.
Instance Scope
To be sure that the same instance is injected, you could register your DbContext as Singleton.
For example:
var builder = new ContainerBuilder();
builder.RegisterType<DbContext>().SingleInstance();
Or, depending on your needs, you could register it using the Instance Per Request scope:
var builder = new ContainerBuilder();
builder.RegisterType<DbContext>().InstancePerRequest();
Note: You may find this article written by Martin Fowler useful.
Im looking for an answer to what I suspect is a fairly basic question.
I am starting out using Windsor now and am struggling to figure out how to register an interface...
In my app I have an IRepository interface which is passed into my controllers in their constructors. I want Windsor to resolve these dependencies for me but am struggling to figure out how to do this.
So my IRepository looks a little like this:
public interface IRepository : IDisposable
{
List<string> GetList();
}
This is implemented in two classes:
public class Repository1 : IRepository
{
public List<string> GetList(){...}
}
public class Repository2 : IRepository
{
public List<string> GetList(){...}
}
My Controller looks a little like this:
public class HomeController : Controller
{
private readonly IRepository _repo;
public HomeController(IRepository repo)
{
_repo = repo;
}
...
Now I would like to register IRepository to resolve to either of the implementations Repository1 or Repository2 (Eventually I want to be able to figure out which Repository is availabe in other assemblies and load whichever is available)
Now, I have register the classes and change the constructor to take an instance of one of the classes and that works, but I want to do it against the interface... and thats where Im struggling.
I would also like this to be generic enough that if I have an IWhatever and a class that implements it that windsor would be able to resolve that too without having to register each and every one...
I have this (Which works)
container.Register(Classes.FromAssemblyContaining<Repository1>()
.BasedOn(typeof(IRepository))
.WithService.AllInterfaces()
.LifestyleTransient());
But its only registering Repository1... Any help appreciated, in the mean time Ill be back reading the documentation again and seeing if it sinks in this time!
Thanks
I think that what happens is that you are registering both your repositories, but since your controller only asks for one repository Windsor returns the first one by default.
What you could do to check whether the repositories is to call container.ResolveAll() just after registration; i think that you will get two results.
To correct this, either you must tell your controller that it must resolve a list of repositories (i.e. IRepository[]) or you must narrow down the repository type that is expected. For example if your controller was Controller<T> and your repositories were IRepository, the selection would occur depending on the type of T.
Found the answer:
http://mikehadlow.blogspot.co.uk/2010/01/10-advanced-windsor-tricks-2-auto.html?m=1
this is pretty much what i was looking for, thanks for the help everyone!
Please help me out, how should I pass DBContext object to the constructor of MyEntityRepsitory class?
For example:
public interface IRepository<T> where T: class
{
}
public class Repository<T> : IRepository<T> where T : class
{
private readonly DbContext _dbContext;
public Repository(DbContext dbContext)
{
_dbContext = dbContext;
}
}
public interface IMyEntity : IRepository<MyEntity>
{
MyEntity GetSingle(int Id);
}
public class MyEntityRepository : Repository<MyEntity>, IMyEntity
{
public MyEntityRepository() : base(mydbContext){}
}
I am new to design patterns and implementing repository pattern for my data access layer. I never used Structure map / Unit of Work pattern.
I want to know, how many ways I can create DbContext object so that I can pass.
And please explain me the difference of various approaches.
In the above example class named MyEntityRepository has a constructor and which passes dbContext object to the Repository class constructor. Please tell me how to do that.
Many thanks.
Edit
As per #Trevor de Koekoek's comment, direct injection of a wrapper owning a DbContext can be problematic from a threading and transaction boundary point of view.
In hindsight, injection of a factory is preferable, and used like so:
public ConsumingClass(IRepositoryFactory injectedRepositoryFactory)
And then (if holding the reference to the factory)
using (var applesRepository = _injectedRepositoryFactory.CreateRepository<Apples>())
{
... do something with apples
}
or by implementing IDisposable on the class.
This gives the client a clean repository, and forces the client to take ownership of the repository instance.
Original Answer
As you've suggested, you should configure an IoC container (like StructureMap) to do this for you - classes which need to use an IRepository<T> will have an instance injected via either constructor or setter injection. This IMO is the cleanest implementation, as it has testability, the coupling to Repository is via Interface only, and neither Repository nor consuming classes are coupled to the IoC container.
e.g. using Constructor injection:
public class ConsumingClass
{
public ConsumingClass(IRepository<Apples> injectedApplesRepository)
}
The mapping of IRepository to its concrete class is done via the IoC Bootstrapper (or in config). For improved testability, I would also couple your repository to IDbContext, not to DbContext, e.g.
private void ConfigureIoC()
{
For<IDbContext>().Use<MyDbContext>();
For<IRepository<T>>().Use<Repository<T>>();
// ... etc
}
When your consuming class is built up by the IoC, it will recursively detect all dependencies (IRepository<T>, and then in turn IDbContext) and built these up, and their depedencies etc.
The other alternatives are patterns like Service Locator Pattern (now often regarded as an anti pattern, as it couples classes to the locator), and Factory Method.
I am looking to see how Ioc/Di can simplify wiring the following classes I use often.
Consider a library that has an abstract notion of an Entity and an interface for a data access object:
public abstract class EntityWithTypedId<TId> : IEntityWithTypedId<TId>{...}
public interface IDao<T, TId> where T : IEntityWithTypedId<TId>
For the dao, I have one implementation for NHibernate as well as a fake dao I find useful for testing:
// has an NHib implementation
public class Dao<T, TId> : IDao<T, TId> where T : EntityWithTypedId<TId> {...}
public class DaoFakeBase<T> : IDao<T, int>, IDisposable where T : IEntityWithTypedId<int> {...}
I currently do the following to define an Entity and Dao type for a given project:
/// <summary>
/// <see cref="IEntityWithTypedId{IdT}"/> with an int for an id
/// </summary>
[Serializable]
public abstract class Entity : EntityWithTypedId<int>
{
}
public class Dao<T> : Dao<T, int> where T : Entity
{
protected Dao(ISessionFactory sessionFactory) : base(sessionFactory) { }
}
Can I use a DI tool to define the Entity instead? Can someone show me a code sample of how to do it if so?
Can you also lay out how I might tell my test assembly to use DaoFakes and production to use NHib.Dao
I have been looking at Windsor, mostly because NHibernate contrib projects use it, but am also interested in MEF, AutoFac and Ninject, in that order. I realize that MEF is not an IoC container in the sense that Windsor is. From what I can see with Windsor I would use Installer classes, maybe an EntityInstaller and a DaoInstaller, although I might be missing a FActory type of object here too.
Cheers,
Berryl
UPDATE # KeithS
Are you saying to change something like:
class MyViewModel(IDao<MyClass, int> dao) {...}
becomes something like
class MyViewModel(Func<IDao<MyClass, int>, obj> getDaoFunc) {
_dao = getDaoFunc(this);
}
In your example...
class MyViewModel(IDao<MyClass, int> dao) {...}
...IDao would get resolved at runtime based on a previous registration within your container. The syntax for a Prism/Unity implementation is below...
IUnityContainer.RegisterType<IDao..., DaoFakeBase...>();
The RegisterType takes place within IModule.Initialize() of a given module as defined in the UnityBootstrapper class.
protected override IModuleCatalog GetModuleCatalog()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(project.Init));
return catalog;
}
You can also register a given type based on a lifetime manager; to behave as a Singleton...
IUnityContainer.RegisterType<IShellController, ShellController>(new ContainerControlledLifetimeManager());
...where the IShellController resolved instance will remain the same returned instance throughout the lifetime of the IUnityContainer.
UPDATE:
Using your code the registration would look like this...
public interface IDao<T, TId> where T : IEntityWithTypedId<TId>
{ }
public class Dao<T, TId> : IDao<T, TId> where T : EntityWithTypedId<TId>
{ }
public class TId
{ }
public abstract class EntityWithTypedId<TId> : IEntityWithTypedId<TId>
{ }
public interface IEntityWithTypedId<TId>
{ }
IUnityContainer.RegisterType<IEntityWithTypedId<TId>, EntityWithTypedId<TId>>();
IUnityContainer.RegisterType<IDao<IEntityWithTypedId<TId>, TId>, Dao<IEntityWithTypedId<TId>, TId>>();
IDao<IEntityWithTypedId<TId>, TId> dao = IUnityContainer.Resolve<IDao<IEntityWithTypedId<TId>, TId>>();
I would not use IoC to register the relationship between DAOs and their types (which is basically what you'd be doing). This will lead to you using the IoC container as a "service locator", a known anti-pattern where you pass the IoC container into objects that will use it to get the DAO they need.
I think the best way to simplify this from a consumption perspective would be to define a strategy pattern, using a factory class or method:
public Dao<T, TId> GetDaoFor<T, TId>(T objectInstance) where T:EntityWithTypedId<TId>
{
//Here, you could use a Dictionary, Linq with some reflection, etc.
}
This one method can be injected as a delegate into classes dependent upon DAOs. The difference is that classes that need a DAO are dependent on a method that can give it to them, which can be provided by the IoC container; they are NOT dependent on the container itself (which is the primary source of evil inherent in the "service locator" pattern). This reduces the number of things you'd have to change if you re-wrote how you got these DAOs.
EDIT: A bit off-topic, but I opened the door:
The service location pattern is generally to be avoided, because it results in code that relies on the service locator. For instance, the following is common in code where the IoC has been exposed at child levels:
private IDependency _dependency;
public IDependency MyDependency
{
get {
_dependency = _dependency ?? IoC.Resolve<IDependency>();
return _dependency;
}
}
While this seems like a nice pattern (dependencies are lazily initialized, consuming code doesn't need to know about dependencies of the child, and you always* get a reference), this code will ALWAYS require the IoC singleton to exist. You can change the IoC framework behind it, you can remove the third-party tool altogether and roll your own, but this class will always require something on which to statically call Resolve<IDependency>().
You also don't ALWAYS get a reference; you get a reference only if you properly registered IDependency with IoC. This produces two more weaknesses; 1) you don't know what the class will need without opening it up, and 2) if/when the call fails, it will fail deep in the bowels of the dependent class' inner workings. If you develop a new class, and plug it into IoC, it may pass integration, and even work in production for a while, until you start getting weird "object reference set to null" errors in really weird places in code, which are, trust me, a nightmare to debug.
Lastly, unit-testing service-locator-pattern code is more difficult, for the simple reason that you must mock the service locator as well as the dependency provided by the service locator. You can leave the production service locator in use, and simply register mocked classes as the dependencies, but that's not a unit test; the test relies on, and thus to some extent tests, that the integration of the class and its service locator works as expected. That's an integration test.
By contrast, dependency injection patterns free you from any dependency on how dependencies are resolved. The only requirement (in constructor-injection) is that they be around when the class is created. This has several advantages:
If not using an IoC framework, you have to know what the class will need to instantiate it.
If using an IoC framework, you get a runtime error when attempting to instantiate the dependent class, not sometime later when the object actually gets resolved.
When testing a dependent class, you can more easily mock the dependency, because the dependency does not have to be fed in via the service locator.
You can in most IoC frameworks still lazily initialize dependencies by providing a factory method instead of the actual dependency to the constructor. The above pattern then calls that delegate, which could come from anywhere, instead of a static named method which is satisfied by one and only one construct in the entire codebase.