I have a service that stores the applications state. For this reason I've made it singleton. It's passed into the constructor of some WebAPI controllers to expose some of it's state and functions. A permanent reference is held by a background worker which is continuously doing things and making state changes.
This state service has some persistence in that certain changes result in db writes. These are non blocking but that's besides the point. The single service needs to reference one or more repositories. A repository is just a generic class that has a get and insert method for it's given type. It's passed an IDbConnection into it's constructor. The repositories themselfs are passed into the singleton service constructor.
DI does the build up of the chain and it throws an error due to singleton objects (the service) depending on transient objects (the repositories). I wasn't obvious to me at first but this does make sense and could cause concurrency issues.
https://simpleinjector.readthedocs.org/en/latest/LifestyleMismatches.html
The DI suggestions are make the dependancies singleton, make the owner not singleton or pass in a factory for the depentancies instead. Therein lies my quandary.
We're talking about the interface between singleton and non-singleton and how that is bridged. The service needs to be singleton of the far left of the graph, and the IDbConnecton must be transient on the far right, so a factory is needed to be the bridge but where to put it.
I could inject a factory that creates repositories but that would mean creating a new repository object for each individual repository operation. This seems quite a wasteful thing to do. Admittedly the repository doesn't hold any state, but it does seems logical then to make the repository itself singleton and give it a factory that produces IDbConnections.
The factory could in fact just wrap a connection pool but that's implimentation detail. It feels somehow dirty making a repository singleton to satisfy the dependency chain, even though it does make logic sense when I think it through.
Id appriciate it if anyone could sanity check me. It feels like there is some kind of mistake in my reasoning, or that I'm nibbling around the edges of a pattern that I don't know about.
As I was reading, the factory approach was already in my mind before you had introduced it. For me, the RepositoryFactory seems the most attractive approach as they sound inexpensive to create and can then be given any scoped dependencies they might need. I.e. a connection shared across more than one repository.
Related
The project I'm working on has a lot of boilerplate code for passing Repository objects around. The parent object creates a repository, passes it to any utility / helper methods to do some specific work, then in the end the parent object calls commit or save on the repository. And many times these utility/helper methods calls other methods, which also requires the repository. For one, we are definitely using the Repository Pattern incorrectly, since many of these helper methods really just uses the repositories as a DAO or even just a DB connection, run a quick query and be done with it. My question is what is the best way to avoid having to pass these repositories around?
The most primitive way would be to create the repositories in these helper methods, then destroy them (using clauses), and there are obvious downsides to that, and it's against DRY.
I also see examples of people registering these repositories as services, and use them that way.
Please take thread safety into consideration.
What are the expert opinions on this? Any example would be much appreciated.
PS. I'm a senior level Java guy but almost entry level on C#, so any java-related comparison would be great too.
The 'correct' way to register and retrieve Repositories is with a DI Container (I recommend Autofac
builder.RegisterType<MyRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
InstancePerLifeTimeScope means it's thread scoped so only one instance per thread. Every object needing the repository will have the repository interface as the constructor dependency. For some services, the repository can be a method argument.
The repository will use a (micro)ORM to 'talk' with the database. There are some cases where you need data or even some objects which can be retrieved directly from the db. In that case you have a service and not a repository, although both implementations (not interfaces) belong in the DAL.
I'm assuming that all the services and repositories are passed as abstractions, so every object needing a service or repository will know only about a IService or IRepository. The DI Container will inject the concrete types, the client objects don't need to know about those.
We are working on an application to process various XML messages and load them into a datastore. One of the devs I am working with created a Singleton Factory utilizing reflection to create an instance of the appropriate message subclass. My question is around using a singleton for the factory...(Using the samething for building the SqlCommand object need to pass to DB). The factory definitely makes sense here the part I am fuzzy about is using Singleton in conjunction with the Factory.
I have read a lot of postings, stackoverlow responses, etc and it still isn't clear to me why for this scenario we would use that pattern (Singleton with factory...I would assume just use a factory pattern?).
Just trying to better understand as what I have gathered you would want to use Singleton when you want to ensure one and only one interface?
Singletons do not ensure a single interface; they ensure a single instance of an object that is accessible globally to other objects. An example of where you might want to use a singleton is when you need a counter that is accessible from anywhere in the application. In other words the state of that single object is maintained throughout the applications lifetime.
Factories on the other hand are used to create object where you do not necessarily know the exact type of class that is returned. For example, you may have a factory that returns an automobile object but the exact class that is returned might be a Volkswagen or it might be a Ferrari.
Factories are used a lot for dependency injection (DI). So in the example you give you can use a factory to return an object that interfaces with a DB, but the actual class may interface with a DB using SQL statements or maybe it is another class that uses an object-relational mapping (ORM) framework. This decouples the actual database interface/implementation from the rest of the application and allows more flexibility in changes to DB access going forward. The factory could even return a mockup of the DB access that can be used for unit testing. DI can be used to change which method is used at run-time. I would definitively recommend using Factories for these reasons.
Factories can also return singletons. So the question to ask in determining if you need a singleton is, do I need to maintain state across the application for all of the objects that will access this. An example of wanting to maintain state is that you want to keep the connection open to the database for any object that accesses this DB object for the life of the application. Not suggesting you do this but it just an example of why you may want to maintain the state information of that object for the life of the application.
I've been using IoC (mostly Unity) and Dependency Injection in .NET for some time now and I really like the pattern as a way to encourage creation of software classes with loose coupling and which should be easier to isolate for testing.
The approach I generally try to stick to is "Nikola's Five Laws of IoC" - in particular not injecting the container itself and only using constructor injection so that you can clearly see all the dependencies of a class from its constructor signature. Nikola does have an account on here but I'm not sure if he is still active.
Anyway, when I end up either violating one of the other laws or generally ending up with something that doesn't feel or look right, I have to question whether I'm missing something, could do it better, or simply shouldn't be using IoC for certain cases. With that in mind here are a few examples of this and I'd be grateful for any pointers or further discussion on these:
Classes with too many dependencies. ("Any class having more then 3 dependencies should be questioned for SRP violation"). I know this one comes up a lot in dependency injection questions but after reading these I still don't have any Eureka moment that solves my problems:
a) In a large application I invariably find I need 3 dependencies just to access infrastructure (examples - logging, configuration, persistence) before I get to the specific dependencies needed for the class to get its (hopefully single responsibility) job done. I'm aware of the approach that would refactor and wrap such groups of dependencies into a single one, but I often find this becomes simply a facade for several other services rather than having any true responsibility of its own. Can certain infrastructure dependencies be ignored in the context of this rule, provided the class is deemed to still have a single responsibility?
b) Refactoring can add to this problem. Consider the fairly common task of breaking apart a class that has become a bit big - you move one area of functionality into a new class and the first class becomes dependent on it. Assuming the first class still needs all the dependencies it had before, it now has one extra dependency. In this case I probably don't mind that this dependency is more tightly coupled, but its still neater to have the container provide it (as oppose to using new ...()), which it can do even without the new dependency having its own interface.
c) In a one specific example I have a class responsible for running various different functions through the system every few minutes. As all the functions rightly belong in different areas, this class ends up with many dependencies just to be able to execute each function. I'm guessing in this case other approaches, possibly involving events, should be considered but so far I haven't tried to do it because I want to co-ordinate the order the tasks are run and in some cases apply logic involving outcomes along the way.
Once I'm using IoC within an application it seems like almost every class I create that is used by another class ends up being registered in and/or injected by the container. Is this the expected outcome or should some classes have nothing to do with IoC? The alternative of just having something new'd up within the code just looks like a code smell since its then tightly coupled. This is kind of related to 1b above too.
I have all my container initialisation done at application startup, registering types for each interface in the system. Some are deliberately single instance lifecycles where others can be new instance each time they are resolved. However, since the latter are dependencies of the former, in practice they become a single instance too since they are only resolved once - at construction time of the single instance. In many cases this doesn't matter, but in some cases I really want a different instance each time I do an operation, so rather than be able to make use of the built in container functionality, I'm forced to either i) have a factory dependency instead so I can force this behaviour or ii) pass in the container so I can resolve each time. Both of these approaches are frowned upon in Nikola's guidance but I see i) as the lesser of two evils and I do use it in some cases.
In a large application I invariably find I need 3 dependencies just to access infrastructure (examples - logging, configuration, persistence)
imho infrastructure is not dependencies. I have no problem using a servicelocator for getting a logger (private ILogger _logger = LogManager.GetLogger()).
However, persistence is not infrastructure in my point of view. It's a dependency. Break your class into smaller parts.
Refactoring can add to this problem.
Of course. You will get more dependencies until you have successfully refactored all classes. Just hang in there and continue refactoring.
Do create interfaces in a separate project (Separated interface pattern) instead of adding dependencies to classes.
In a one specific example I have a class responsible for running various different functions through the system every few minutes. As all the functions rightly belong in different areas, this class ends up with many dependencies just to be able to execute each function.
Then you are taking the wrong approach. The task runner should not have a dependency on all tasks that should run, it should be the other way around. All tasks should register in the runner.
Once I'm using IoC within an application it seems like almost every class I create that is used by another class ends up being registered in and/or injected by the container.*
I register everything but business objects, DTOs etc in my container.
I have all my container initialisation done at application startup, registering types for each interface in the system. Some are deliberately single instance lifecycles where others can be new instance each time they are resolved. However, since the latter are dependencies of the former, in practice they become a single instance too since they are only resolved once - at construction time of the single instance.
Don't mix lifetimes if you can avoid it. Or don't take in short lived dependencies. In this case you could use a simple messaging solution to update the single instances.
You might want to read my guidelines.
Let me answer question 3. Having a singletons depend on a transient is a problem that container profilers try to detect and warn about. Services should only depend on other services that have a lifetime that is greater than or equals to that of their own. Injecting a factory interface or delegate to solve this is in general a good solution, and passing in the container itself is a bad solution, since you end up with the Service Locator anti-pattern.
Instead of injecting a factory, you can solve this by implementing a proxy. Here's an example:
public interface ITransientDependency
{
void SomeAction();
}
public class Implementation : ITransientDependency
{
public SomeAction() { ... }
}
Using this definition, you can define a proxy class in the Composition Root based on the ITransientDependency:
public class TransientDependencyProxy<T> : ITransientDependency
where T : ITransientDependency
{
private readonly UnityContainer container;
public TransientDependencyProxy(UnityContainer container)
{
this.container = container;
}
public SomeAction()
{
this.container.Resolve<T>().SomeAction();
}
}
Now you can register this TransientDependencyProxy<T> as singleton:
container.RegisterType<ITransientDependency,
TransientDependencyProxy<Implementation>>(
new ContainerControlledLifetimeManager());
While it is registered as singleton, it will still act as a transient, since it will forward its calls to a transient implementation.
This way you can completely hide that the ITransientDependency needs to be a transient from the rest of the application.
If you need this behavior for many different service types, it will get cumbersome to define proxies for each and everyone of them. In that case you could try Unity's interception functionality. You can define a single interceptor that allows you to do this for a wide range of service types.
I'm a newbie to Dependency Injection. I have never used and never even undestood what it is exatcly all about, but after my last attack on this topic I found out that is a way of uncoupling an object and its dependencies, once they are not responsible for instantiating the concrete versions of its dependencies anymore, as now the container will do it for us and deliver the ready object in our hands.
Now the point is; "when should I use it?", ALWAYS??? Actually, as I'm a newbie and have never even seen a project that uses this pattern I can't undestand how I should apply it to my domain objects!!! It seems to me that I will nevermore instantiate my objects and the container will always do it for me, but then comes some doubts...
1) What about oobjects that part of its dependencies comes from the UI, for example;
public class User(String name, IValidator validator)
Say that I get the user name from the UI, so how will the conatiner know it and still delliver this object for me?
2) Theres other situation I'm facing; if a dependency is now an object that is already instantiated, say... a SINGLETON object, for example . I saw theres settings regarding out the scope of life of the dependency beign injected (im talking about Spring.NET, eg; http request scope)... BUT, request and other web related things are on my presentation layer, so how could I link both my presentation layer and my domain layer without breaking any design rule (as my domain should be totally unaware of where its is being consumed, not to have layer dependency, etc)
Im eager to hear from you all. Thanks very much.
In general, once you go IoC, you tend to want to register EVERYTHING with IoC and have the container spit out fully-hydrated objects. However, you bring up some valid points.
Perhaps a definition of "dependency" is in order; at its broadest, a dependency is simply a set of functionality (interface) that a given class requires a concrete implementation of in order for the class to work correctly. Thus, most non-trivial programs are full of dependencies. To promote ease of maintenance, loose coupling of all dependencies is generally preferred. However, even when loosely coupled, you don't need to automate instantiation of dependencies if those objects require specialized information that you don't want to pollute your IoC registry with. The goal is to loosely couple usage, not necessarily creation.
Concerning point 1, some IoC frameworks don't do well with being given external parameters. However, you can usually register a delegate as a factory method. That delegate may belong to an object like a Controller that is given external information by the UI. Logins are a perfect example: Create an object, say a LoginController, and register it with IoC as your ILoginController. You'll reference that controller on your Login page, it will be injected when the Login page is instantiated, and the login page will pass it the credentials entered. The Controller will then perform authentication, and will have a method GetAuthenticatedUser() that produces a User object. You can register this method with IoC as a Factory for Users, and whenever a User is needed, the factory delegate will either be evaluated, or passed wholesale to the dependent method which will call it when it really needs the User.
On point 2, setting up a single instance of an object is a strength of the IoC pattern. Instead of creating a true singleton, with a private instance constructor, static instance and static constructor to produce an instance, you simply register the class with IoC and tell it to only instantiate it once and use that one instance for all requests. The strength is the flexibility; if you later want there to be more than one instance, you just change the registration. You won't break any design pattern rules either way; the view will always have a Controller injected, whether that Controller is the same for all pages or a new instance per request.
1) this contructor is probably not the right one to use, may be you are injecting the validator in the wrong place/way.
2)Neighter View nor Model and nor Controller should be aware of there is an IoC, it should lie in the background architecture ( where MVC components are actually instantiated )
You should use IoC when you feel the architecture can became complex and has to be mantained by many people. If you are writing an enterprise application, or a UI you think to extend with plugins, you probably need it, if you are writing a command line utility, probably not.
You should use dependency injection whenever you want any of the following benefits:
The ability to replace modules easily
The ability to reuse modules between parts of the application, or different applications
When you want to do parallel development, so that components of a system can be developed in isolation and in parallel because they depend on abstractions
When you want easier maintenance of a system because of loose coupling
When you want testability (a specialisation of replacing modules). This is one of the biggest reasons for using DI
To answer your other questions:
1) You can configure many IoC containers so that certain constructor parameters can be specified, whilst others are resolved by the container. However, you may need to think about refactoring that piece of code, as a UserFactory may be more appropriate which takes the validator dependency, and has a NewUser method which takes a user name and returns a new user (either instantiating it directly or resolving from the container).
2) Each application you build will have a composition root, where your container is configured, and the root object is resolved. Each app will therefore have its own IoC configuration, so there is an expected link between the application type and the configuration settings. Any common abstraction registrations can be placed in configuration code which can be shared amongst all applications.
More specifically, What's the best approach for classes where state matters, within an application which implements Dependency Injection.
Say I need access to an object that's in a particular state. For example, this object might have been initiated in a different thread, or by a process I have no control over.
A good example of an object like this that already exists in .NET is the HttpContext.
In this case, Microsoft decided to go with the Static approach, so I just say:
var currentObj = HttpContext.Current;
And this gives me a particular instance of an object without having to worry where it came from.
The problem with the Static approach is that it doesn't play very nicely with dependency injection.
The other option is to configure your certain class as a Singleton in your IoC Container. This means that you can inject it, and depending on the current IoC Container config it'll be the correct instance of the class.
However, the downfall of this approach is that the stateful importance of the object is no longer explicit in the code, it's not obvious by looking at it. With the Static class used to access and instance it's more clear that the state is important. Maybe that doesn't matter though.
So, is there a pattern that helps me out here?
Context:
For context, I'm working on an application which has many instances of a class performing IO operations. They exists within their own threads.
I want to be able to interact with those objects (background tasks) via a web interface, so a Controller. I want to be able to interrogate them, and manipulate them etc.
Update:
Sorry, I think my use of the term "stateful" is a bit misleading. let me explain some thing:
"state" is probably the wrong word. I mean communicating with an object whereby I don't have control over it's lifecycle.
It is funny that I use "stateful" when talking about static classes. That's why I gave the HttpContext example, as that exactly what it does. The Current property gets you a very specific instance, not any new instance.
When I say that static doesn't play nice with DI, I meant, you can't inject Static classes. I could create a wrapper, yes, but I'm just pushing the problem elsewhere no?
I should have been more clear about my definition of Singleton. I meant a Singleton lifestyle, as defined in an IoC Container.
I always prefer Singleton over static. In fact, I almost never use statics in my own classes.
True singletons and static classes are both very difficult to write automated tests against. Do you mean a single instance looked up at runtime? That would make sense to me but I don't know the right construct to use in C#. The analog in Java is JNDI.
Neither or both. Presuming the stateful dependency is thread-safe the better approach is to build at least a basic layer of abstraction around said dependency then inject said abstraction into your classes. Singleton vs static becomes pretty immaterial then.