I am new to dependency injection, and I am trying to solve an issue. I have two services. Each of these services have methods who need eachother.
For instance: SiteManager have methods where it needs my ForumManager. My ForumManager have methods where it needs my SiteManager.
I have the following two classes:
public class SiteManager:ISiteManager
{
public IForumManager ForumManager { get; set; }
public SiteManager()
{
this.ForumManager = new ForumManager();
}
}
public class ForumManager:IForumManager
{
public ISiteManager SiteManager { get; set; }
public ForumManager()
{
this.SiteManager = new SiteManager();
}
}
Very obviously this will result in a stack overflow exception, as they call eachother. I've read a lot of posts here, and I think I just need a small hint on how to solve this. I have my interfaces in their own assembly.
I thought about putting the dependencies in their own property so when they are used, they are made. However, is this best practice?
I do not use an IoC container (and I haven't used that before).
Any hints on how to solve this particular issue in a "best practice" way! :-)
You should not be calling new within your classes, that will tightly couple them. The correct pattern for IOC that will allow you to test each class separately using mocks is:-
public class SiteManager:ISiteManager
{
private readonly IForumManager forumManager;
public SiteManager(IForumManager forumManager)
{
this.forumManager = forumManager;
}
}
public class ForumManager:IForumManager
{
private readonly ISiteManager siteManager;
public ForumManager(ISiteManager siteManager)
{
this.siteManager = siteManager;
}
}
But, that doesn't solve the mutual recursion. The easiest way to solve that is to not use constructor injection for one of the classes, but use property injection instead, i.e. put the SiteManager back to a public property on the ForumManager and set it after creating both objects.
Your setup code then does:-
IForumManager forumManager = new ForumManager();
ISiteManager siteManager = new SiteManager(forumManager);
forumManager.SiteManager = siteManager;
Another alternative would be to pass a ForumManagerFactory into the SiteManager, e.g. a Func<ISiteManager,IForumManager>.
ISiteManager siteManager = new SiteManager((s) => new ForumManager(s));
Inside the site manager you can then call the Func, passing this to get the IForumManager. The ForumManager gets an instance of the SiteManager and the SiteManager has the ForumManager object.
When using MVP with winforms and AutoFac, I had this exact same issue with the view referencing the presenter and the presenter referencing the view. The way I got around it is to have one of your classes pass itself to the other using an Initialize method. I am not sure if this is best practice, but I have seen it suggested before (this question about mvp)
So for the implementation details:
public class SiteManager:ISiteManager
{
public IForumManager ForumManager { get; set; }
public SiteManager()
{
}
public Initialize(IForumManager forumManager)
{
ForumManager = forumManager
}
}
public class ForumManager:IForumManager
{
public ISiteManager SiteManager { get; set; }
public ForumManager(ISiteManager siteManager)
{
this.SiteManager = new SiteManager();
this.SiteManager.Initialize(this);
}
}
Edit Actually would probably go with the other solutions posted, I was just looking at this purely from a circular dependency point of view
what you are doing and what you are suggesting both will cause stack overflow exception. i don't know why will you want to do something like that and you are not giving any hints on that but i guess i can offer you to create a manager, maybe a singleton, maybe just with static method and do:
public static void DoStuff(ISiteManager sm, IForumManager fm)
{
// your code here can use the best of both without SO
}
and not holding ISiteManager in ForumManager and IForumManager in SiteManager
You clearly can't have interdependant classes. What you need to do is to create a separate class and move there the methods which use the same time forum manager and sitemanger: Here is a sample 3rd class:
class ForumAndSiteManager
{
public ForumAndSiteManager(ISiteManager siteMaanger, IForumManager forumManager)
{
//save the injected object to private fileds
}
//define methods which will use both sitemanager and forum manager
}
This way you will brake the circular depedency
You should definitely avoid circular dependencies. I mean A depends on B and B on A.
This is like a cancer of your context dependencies. We used spring.net framework which contrary to java's version is unable to switch on a failing system if it discovers this kind of dependency. I have to say that this brings us only mess and hours of spring's logs searching and analyzing.
We defined almost 200 without any problem but once we added just another bean along with Lazy reference it failed down. This is almost impossible to untangle our solution to avoid it right now so we hook and hook and hook whilst it fails :-(
Related
I have a question concerning lifetime scopes in Autofac.
It is allowed to create multiple scopes in different places in the application to resolve types?
In official documentation there is such a statement:
Note: generally speaking, service location is largely considered an anti-pattern That is, manually creating scopes everywhere and sprinkling use of the container through your code is not necessarily the best way to go. Using the Autofac integration libraries you usually won’t have to do what we did in the sample app above. Instead, things get resolved from a central, “top level” location in the application and manual resolution is rare. Of course, how you design your app is up to you.
What if I have several view models and I need to resolve some types in each one?
Example:
public class ClassA
{
//some code here
}
public class ClassB
{
//some code here
}
public class ClassC
{
//some code here
}
public class ViewModelA
{
public ViewModelA()
{
}
public void Method()
{
//some code here
using (var scope = Container.BeginLifetimeScope())
{
var typeC = scope.Resolve<ClassC>();
//some code here
}
}
}
public class ViewModelB
{
public ViewModelB()
{
}
public void Method()
{
//some code here
using (var scope = Container.BeginLifetimeScope())
{
var typeA = scope.Resolve<ClassA>();
var typeB = scope.Resolve<ClassB>();
//some code here
}
}
}
Assuming that all types are registered in the container - is spreading such scopes across the app is a good practice? How do you understand that?
Best regards.
TL;DR
I have a question concerning lifetime scopes in Autofac. It is allowed to create multiple scopes in different places in the application to resolve types?
Yes, it is allowed, even though it is considered not the best way to go - but definitely not the prohibited one.
What if I have several view models and I need to resolve some types in each one?
Just resolve them through constructor injection as it was suggested by #Raymond. You don't need scopes for something as simple as just resolving stuff.
Now, let's talk this through a little bit.
First of all, how do you use constructor injection? There's nothing simpler than that. Let's modify your example just a bit:
public class ClassA
{
//some code here
}
public class ClassB
{
//some code here
}
public class ClassC
{
//some code here
}
public class ViewModelA
{
private ClassC typeC;
// this is a constructor injection - yes, it's that simple.
public ViewModelA(ClassC _typeC)
{
typeC = _typeC;
}
public void Method()
{
typeC.doStuff();
}
}
public class ViewModelB
{
private ClassA typeA;
private ClassB typeB;
public ViewModelB(ClassA _typeA, ClassB _typeB)
{
typeA = _typeA;
typeB = _typeB;
}
public void Method()
{
typeA.doStuff();
typeB.doAnotherStuff();
}
}
That's it. You just specify parameters in the constructor and save those parameters somewhere in the private fields of the class - and you're good to go. Just use those objects assuming they do exist for sure. (They can be optional though, but I'll skip that for now). If autofac is unable to resolve some dependency it will throw an exception - thus if your class got created you can be absolutely sure that all the dependencies were resolved and provided to it in the constructor parameters. (Again, I'll skip some more complicated scenarios for the sake of brevity and clarity).
What does it give us? Well, now classes ViewModelA and ViewModelB know nothing about any containers or DI in general. All they know is that someone (read: "container") will somehow provide a couple of parameters of specified types (which are usually interfaces) from outside. The class itself now knows nothing about who will create its dependencies, where, when and how - it's not its concern anymore. This is the whole point of dependency injection: removing the concern of managing dependencies.
Next thing is - where are the scopes in this picture? Well... nowhere. :) That's the ideal picture: the services are completely unaware of the existence of the DI container.
But what is a lifetime scope anyways? It is a mean of controlling (surprise!) life time of the objects that are resolved from it. You typically don't need it, unless you are dealing with some edge-case scenarios.
Let's take a look at the extremely simplified example. Say, you have some job that needs to perform some kind of requests to external resources on schedule. However, the method that performs requests is actually generic: it does not know beforehand what exact type of request it is performing because it is defined by the type parameter of the method which will only be known in the runtime.
Also, let's say that you have another requirement: you need to not keep api services in the memory but rather create them only for performing the request and then discard them right away after work is done.
It could look something like the following:
abstract class SomeSpecialApi<TSomeTypeParam> { // just some common base type
public abstract string doGetStuff();
}
class SomeSpecialApi1 : SomeSpecialApi<SomeTypeParam1> where SomeTypeParam1 : TSomeTypeParam {
private HttpClient _client;
public SomeSpecialApi(HttpClient client) {
_client = client;
}
public override string doGetStuff() {
return _client.get(someUrlWeDontCareAbout).Result;
}
}
class SomeSpecialApi2 : SomeSpecialApi<SomeTypeParam2> where SomeTypeParam2 : TSomeTypeParam {
private SomeFtpClient _client;
public SomeSpecialApi(SomeFtpClient client) {
_client = client;
}
public override string doGetStuff() {
// it's just something very different from the previous class
return _client.read(someOtherPathWeDontCareAboutEither).Result;
}
}
class JobPerformer {
private ILifeTimeScope _scope;
public JobPerformer(ILifeTimeScope scope) {
_scope = scope;
}
void PerformJob<T>() {
while (true) {
using (var childScope = scope.BeginLifeTimeScope()) {
var api = childScope.Resolve<SomeSpecialApi<T>>();
var result = api.doGetStuff();
// do something with the result
} // here the childScope and everything resolved from it will be destroyed
// and that's the whole purpose of the lifetime scopes.
Thread.Sleep(1000);
}
}
}
Do you see how it works? Depending on the method's type parameter container will resolve different classes to get the job done. So, instead of creating all the dependencies and then destroying them manually all you need to do is to create your own scope, request an instance of the service you need and then destroy scope after work is done. Scope destruction takes care of destroying all the dependencies which you don't (and shouldn't) even know about. That's definitely an improvement compared to the creation of all the dependencies manually.
However, the disadvantage here is that now JobPerformer class has to know about such a thing as ILifeTimeScope. So it's in some sense similar to the ServiceLocator pattern: we have to know at least who to ask for the dependency, in other words: JobPerformer now knows something about our container. That's what we ideally want to avoid, and there are also other means to achieve it: factories; owned instances; different lifetime policies of service registrations in the container; different kinds of lifetime scopes (at least in autofac); etc.
In the project I'm working on, I've added a base ViewModel class which contains some functionality and dependencies common to all ViewModels. It provides validation, messaging, dispatching and navigation services through the following properties:
IValidateProperties Validator { get; }
IMessenger Messenger { get; }
IDispatcherHelper DispatcherHelper { get; }
INavigationService Navigation { get; }
I use an IoC container to wire my dependencies, however I have a few options for how to handle these dependencies which are common to all of my ViewModels:
Inject them in the constructor. If I did this, then it would require adding these four arguments to the constructor of every single ViewModel and pass them to the base constructor. That's a lot of extra noise added to my code base, which I'd really rather avoid. Also, if I were to add another dependency at some point, that would require changing the constructor of every single ViewModel.
Use property injection. This is the approach I'm working with now. Unfortunately, it means not being able to access these properties until after the ViewModel has been constructed, resulting in the following workarounds:
private IValidateProperties _validator;
public IValidateProperties Validator
{
get => _validator;
set
{
_validator = value;
_validator.ValidationTarget = this;
}
}
private IMessenger _messenger;
public IMessenger Messenger
{
get => _messenger;
set
{
_messenger = value;
MessengerAttached();
}
}
protected virtual void MessengerAttached() { }
Make the properties static and inject them on app startup. This is easy for Messenger, DispatcherHelper and Navigation because they are used as singletons anyway. For Validator, I would need to add a static ValidatorFactory, and instantiate the Validator in the constructor using the factory. This way seems to be the cleanest way to do things, but I have this voice in the back of my head telling me that using statics like this is a bad idea.
I feel like option 1 is out of the question because of the large amount of noisy boilerplate code it would result in being added to my ViewModels. I'm still unsure whether 2 or 3 is the best way to go though. Is there a good reason that using statics is a bad idea in this case, or am I fretting over nothing?
Some people argue that statics lead to untestable code, but in this case it would actually make things easier to test. If I were to go with option 3, I could add the following class for all of my view model tests to inherit:
public abstract class ViewModelTestBase
{
protected readonly IValidateProperties ValidatorMock;
protected readonly IMessenger MessengerMock;
protected readonly IDispatcherHelper DispatcherHelperMock;
protected readonly INavigationService NavigationMock;
protected ViewModelTestBase()
{
ValidatorMock = Substitute.For<IValidateProperties>();
ViewModelBase.Validator = ValidatorMock;
MessengerMock = Substitute.For<IMessenger>();
ViewModelBase.Messenger = MessengerMock;
DispatcherHelperMock = Substitute.For<IDispatcherHelper>();
ViewModelBase.DispatcherHelper = DispatcherHelperMock;
NavigationMock = Substitute.For<INavigationService>();
ViewModelBase.Navigation = NavigationMock;
}
}
So, what concrete reasons are there for not going with approach #3? And if statics really are such a bad idea in this case, what concrete reasons are there for not going with approach #2 instead?
This is more of a theoretical question, but I was wondering what's the best way to pass information within forms. I'll explain my issue:
I have my Mainform class which manages the whole application:
public class Mainform : Form
{
private static AddressBook _addressbook = new AddressBook();
private static TemplateManager _templateManager = new TemplateManager();
/*...*/
}
Furthermore, I have another class which is created by Mainform:
public partial class TemplateLists : Form
{
//To be filled with Mainform's information.
private List<Template> _genericTemplates;
private Client _clientToFill;
//In this case, I decided to pass the information through the constructor.
public TemplateLists(List<Template> genericTemplates, Client client)
{
InitializeComponent();
_genericTemplates = genericTemplates;
_clientToFill = client;
}
}
The issue is that, in order for TemplateLists to recieve the _genericTemplates information, I don't know if it's best done through the constructor, a method or public properties and why. In any case, I know how to implement them all, but I don't know which is best and I don't have any reasons to pick one over another.
Basically your whole question can be brought down to when should one use constructor (ctor) parameters vs properties.
Constructor parameters:
These should be used to set mandatory values on your instance. In other words these are the values without which your class instance cannot function.
Class properties:
These should be used when the values are optional for your object's functioning.
Consider an example, wherein your class pulls data via a service (which in turn talks to database etc). Also you intend to perform some sort of logging. In this case, you know that your class will not work without a service instance but you logging can be optional for this class. So while instantiating StoreManager you have option to set logger if you wish.
public class StoreManager
{
private readonly IService dataService;
public StoreManager(IService dataService)
{
if(dataService == null)
{
// Do not allow to go further.
throw new ArgumentException();
}
this.dataService = dataService;
}
public ILogger Logger
{
get;
set;
}
public IList<Product> GetProducts()
{
var products = dataService.GetProducts();
// logging is optional
if(Logger != null) {
Logger.Trace("Products fetched {0}", products.Count);
}
}
}
Better to use Dependency Injection or Service Location. Check this and this for reference.
There is no such thing as "the best" solution. It really comes down to how the form is used. For example it depends what the generic templates are. If they are necessary for the form to be created, it's a good idea to pass it via constructor to prevent that the form is instanciated incomplete.
If they are optional you could assign the after the form is created.
The implementation details (dependency injection, concrete coupling, etc.) depends on how the form is going to be used.
Background / Goal
We have several "client sites" on our web app that users can switch between
We do a lot of wiring up of objects based on factories that take in the client site ID and create an instance
I would like to inject these dependencies into the classes instead
I also want to make sure I can pass in my own implementations to the constructor for the purposes of unit testing.
We have initially elected to use StructureMap 3.x to do so, but are open to alternatives if they can help us solve this scenario gracefully.
Question
In instances where I require a different dependency based on a client site ID that I'll only get at run-time, what is the appropriate way to set up an IoC container and the appropriate way to request the object from it in order to make it as painless as possible?
Am I thinking about this wrong and unintentionally creating some sort of anti-pattern?
Example Code
Normally we're doing something like the following coming in:
public class MyService
{ DependentObject _dependentObject;
public MyService(int clientSiteID)
{
// ...
_dependentObject = new dependentObjectFactory(clientSiteID).GetDependentObject();
}
public void DoAThing()
{
//...
_dependentObject.DoSomething();
}
}
What I'd like to do:
public class MyService
{ DependentObject _dependentObject;
public MyService(int clientSiteID)
{
// ...
_dependentObject = MyTypeResolver.GetWIthClientContext<IDependentObject>(clientSiteID);
}
public MyService(int clientSiteID, IDependentObject dependentObject)
{
// ...
_dependentObject = dependentObject;
}
public void DoAThing()
{
//...
_dependentObject.DoSomething();
}
}
I would set up the IoC container in such a way that I can use my MyTypeResolver to pass in the clientSiteID, and have the container call my DependentObjectFactory and return the correct object result.
I'm new to IoC containers, and while I'm trying to plow through the literature, I have the feeling it may be easier than I'm making it so I'm asking here.
Probably the simplest way to do this is to use an Abstract Factory. Most IOC frameworks can auto-create them for you, but here's how you can do it manually (I always prefer to do it manually first so I know it works, and then you can check out how the framework can help you automagic it)
Now one thing to mention - I would recommend a slight readjustment of how the final solution works, but I'll go into that once I have shown how it can currently work. Example below assumes Ninject and please excuse any typos, etc.
First create an interface for your dependency
public interface IDependentObject
{
void DoSomething();
}
Then declare empty marker interfaces for each specific implementation of IDependentObject
public interface INormalDependentObject:IDependentObject{};
public interface ISpecialDependentObject:IDependentObject{}
and implement them:
public class NormalDependentObject:INormalDependentObject
{
readonly int _clientID;
public DependentObject(int clientID)
{
_clientID=clientID;
}
public void DoSomething(){//do something}
}
public class DependentObject:ISpecialDependentObject
{
readonly int _clientID;
public DependentObject(int clientID)
{
_clientID=clientID;
}
public void DoSomething(){//do something really special}
}
and of course as you mentioned you may have many more implementations of IDependentObject.
There may be a more elegant way of allowing your IOC framework to resolve at runtime without having to declare the marker interfaces; but for now I find it useful to use them as it makes the binding declarations easy to read :)
Next, declare an interface and implementation of an IDependentObjectFactory:
public interface IDependentObjectFactory
{
IDependentObject GetDependenObject(int clientID);
}
public class DependentObjectFactory: IDependentObjectFactory
{
readonly _kernel kernel;
public DependentObjectFactory(IKernel kernel)
{
_kernel=kernel;
}
public IDependentObject GetDependenObject(int clientID)
{
//use whatever logic here to decide what specific IDependentObject you need to use.
if (clientID==100)
{
return _kernel.Get<ISpecialDependantObject>(
new ConstructorArgument("clientID", clientID));
}
else
{
return _kernel.Get<INormalDependentObject>(
new ConstructorArgument("clientID", clientID));
}
}
}
Wire these up in your Composition Root:
_kernel.Bind<INormalDependentObject>().To<NormalDependentObject>();
_kernel.Bind<ISpecialDependentObject>().To<SpecialDependentObject>();
_kernel.Bind<IDependentObjectFactory>().To<DependentObjectFactory>();
and finally inject your factory into the service class:
public class MyService
{
IDependentObject _dependentObject;
readonly IDependentObjectFactory _factory;
//in general, when using DI, you should only have a single constructor on your injectable classes. Otherwise, you are at the mercy of the framework as to which signature it will pick if there is ever any ambiguity; most all of the common frameworks will make different decisions!
public MyService(IDependentObjectFactory factory)
{
_factory=factory;
}
public void DoAThing(int clientID)
{
var dependent _factory.GetDependentObject(clientID);
dependent.DoSomething();
}
}
Suggested changes
One immediate change from your structure above is that I have left clientID out of the service constructor and moved it to a method argument of DoAThing; this is because it makes a bit more sense to me that the Service itself would be stateless; of course depending on your scenario, you may want to not do that.
I mentioned that I had a slight adjustment to suggest , and it's this; the solution above depends (no pun!) on implementations of IDependentObject having a constructor with this signature:
public SomeDependency(int clientID)
If they don't have that signature then the factory won't work; personally I don't like my DI to have to know anything about constructor params because it takes you out of purely dealing with interfaces and forcing you to implement specific ctor signatures on your concrete classes.
It also means that you can't reliably make your IDependentObjects be part of the whole DI process (i.e whereby they themselves have dependency graphs that you want the framework to resolve) because of the forced ctor signature.
For that reason I'd recommend that IDependentObject.DoSomething() itself be changed to DoSomething(int clientID) so that you can elide the new ConstructorArgument part of the factory code; this means that your IDependentObject s can now all have totally different ctor signatures, meaning they can have different dependencies if needs be. Of course this is just my opinion, and you will know what works best in your specific scenario.
Hope that helps.
Given the following service class in ServiceStack,
public class HelloWorldService: Service
{
public string Get(HelloWorldRequest request)
{
return someOtherClassInstance;
}
}
how would I access someOtherClassInstance? I am puzzled about what best practices are to return objects in specific states? I understand its easy to access static class objects from within HelloWorldService but how about other instances that hold state? I feel extremely hard pressed to believe the best solution is IoC. Any better ways? How can I pass in references to be used? Any suggestions and ideas?
Thanks a lot!
You're over thinking this. A Service in ServiceStack is just a plain C# instance that gets initiated and populated on every request.
By default the built-in Funq registers everything as a singleton, so when you register an instance e.g:
container.Register(new GlobalState());
and reference it in your Service:
public class HelloWorldService: Service
{
public GlobalState GlobalState { get; set; }
public string Get(HelloWorld request)
{
return GlobalState.SomeOtherClassInstance;
}
}
behind the scenes it's always injecting the same instance, and in Funq this is very fast since it's literally just retrieving the instance from an in-memory Dictionary.
But if for whatever reason you don't like that approach than as a Service is still just a C# class so you can use a static property:
public class HelloWorldService: Service
{
public static GlobalState GlobalState = new GlobalState { ... };
public string Get(HelloWorld request)
{
return GlobalState.SomeOtherClassInstance;
}
}
or a Singleton:
public class HelloWorldService: Service
{
public string Get(HelloWorld request)
{
return GlobalState.Instance.SomeOtherClassInstance;
}
}
or however else you want to do it. I recommend using an IOC since it's more testable and consistent with how all other dependences are registered, and I don't really see a good reason not to.