Inject VM to custom control in WPF using Unity - dependency-injection

I am building a WPF based application. I am using Unity to inject all the different dependencies in my application (defined in App.xaml.cs).
In my MainApplication window I have a pretty complex look-less custom control derived from Control(is has about ten more control integrated in it).
I would like to inject a VM into this custom control without coupling it to any other object in my application (except App.xaml.cs of course)
Injection to any WPF window in my application works well, but when I try injecting to the custom control I am facing to different situation:
1. In case I am using
container.RegisterInstance(container.Resolve);
The DI creates a dummy instance of MyCustomControl and injects the VM (using [Dependency] attribute). However this specific instance is not used when I use it in my XAML:
in which case it initializes a new MyCustomControl ignoring any dependencies.
In case I am using
container.RegisterType();
The MyCustomControl completely ignores the injection.
I realize I am probably doing something wrong (not just technically) and I am really trying to avoid coupling this control (which will obviously solve the issue).

I don't know if this is the best solution and found your question while looking for other options but, alas, here is the approach I used to at least get up and running.
I created a base UnityControl class that subclasses Control. In the constructor, I use the ServiceLocator to get a reference to the container. Then I call the BuildUp method to resolve any dependencies on the derived control class. Any dependencies are implemented as read/write properties marked with the DependencyAttribute.
Here's what UnityControl looks like:
public abstract class UnityControl : Control
{
protected UnityControl() : base()
{
Container = ServiceLocator.Current.GetInstance<IUnityContainer>();
Container.BuildUp(this.GetType(), this);
}
protected IUnityContainer Container { get; private set; }
}

Related

Where Do I Declare Unity Container?

I'm just getting started with Unity, and I'm having trouble finding any advice about where to declare my UnityContainer object. Most of the examples that I've seen consist of just a single method where the UnityContainer object is declared at the top, then its mappings are defined, then a few object types are resolved. But how do you handle the container when you need to access it in several places throughout the program? For example, the user clicks on a button which opens a new window and that window needs a controller, which itself needs to resolve several services? I also want some of the services that Unity manages to be singletons, so wouldn't that mean that I'd have to have only a single instance of my UnityContainer throughout my program to manage those singletons?
My first thought is to have my main Program class have a static UnityContainer property or expose some sort of UnityContainerFactory class which manages a singleton UnityContainer instance, but both of those methods seem bad because they create a global property which a lot of things are dependent on.
What's the accepted way of doing this?
As noted in the other answer, you should compose the entire object graph in the Composition Root.
Don't declare the container as a static field since this would encourage developers to use it as a service locator which is an anti-pattern.
How to solve your problem?
Use Dependency Injection.
Here is an example for your special WinForms case:
In your Program.Main method, create the container, register the service (the dependency that you need to use from the other window) and then resolve the main form and run it like this:
UnityContainer container = new UnityContainer();
container.RegisterType<IService, Service>();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(container.Resolve<MainForm>());
In the MainForm, declare a dependency on a Func<SecondForm> where SecondForm is the form that you need to create from the main form when the button is clicked. Consider the following code inside your main form file:
public partial class MainForm : Form
{
private readonly Func<SecondForm> m_SecondFormFactory;
public MainForm(Func<SecondForm> second_form_factory)
{
m_SecondFormFactory = second_form_factory;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SecondForm second_form = m_SecondFormFactory();
second_form.Show();
}
}
Please note that Func<SecondForm> acts as some kind of factory. I use it in this case because unity has a feature to support late construction of dependencies via Func.
The SecondForm has a dependency on IService like this:
public partial class SecondForm : Form
{
private readonly IService m_Service;
public SecondForm(IService service)
{
m_Service = sevice;
InitializeComponent();
}
//Use service here
}
You can now use IService from the second form.
Using Seemann words:
As close as possible to the application's entry point.
Give a look at http://blog.ploeh.dk/2011/07/28/CompositionRoot/ from the great Seemann.
I think that is totally acceptable for the main container to be a static field that get disposed together with your application, just remember to don't tie your classes to your container.
Get noticed of the so called "Service Locator" (again from Seemann: http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/)
Where to declare it really depends on the application, I'd go for the startup class of an owin application or the Main method of a console/WPF app.

"An MVC filter provider has already been registered for a different Container instance." in Simple Injector 2.6

I previously had the setup for property injection in one of my attributes as
Container.RegisterInitializer<PermitAttribute>(initialize =>
{
initialize.QueryProcessor = Container.GetInstance<IQueryProcessor>();
});
And the usage was
public class PermitAttribute : ActionFilterAttribute
{
public IQueryProcessor QueryProcessor { get; set; }
}
but after updating to simpleinjector 2.6.1 The property injection broke. When I am trying to access QueryProcessor object inside PermitAttribute. It resolves null value where as the Simple Injector configuration still has the same property injection via delegate instance .
Is there any breaking change in property injection behavior due to which it was working in v2.5 and its not working anymore in 2.6.1 ?
Update 1:
The Line in the configuration was throwing error for MVC filter provider registration for attributes in v2.6.1
container.RegisterMvcIntegratedFilterProvider();
For that I commented it . And it stopped the property injection working . The property injection was inside one of my attributes . I guess that's the line above which affects it. And its throwing error in v2.6.1
Update 2:
Message
An MVC filter provider has already been registered for a different
Container instance. Registering MVC filter providers for different
containers is not supported by this method.
StackTrace :
at SimpleInjector.SimpleInjectorMvcExtensions.RequiresFilterProviderNotRegistered(Container container)
at SimpleInjector.SimpleInjectorMvcExtensions.RegisterMvcIntegratedFilterProvider(Container container)
at RemsPortal.App_Start.SimpleInjectorInitializer.Initialize() in d:\Projects Work\RemsPortal\V2.0 Web Portal\RemsPortal\App_Start\SimpleInjectorInitializer.cs:line 39
Update 3 :
entire Configuration
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterMvcIntegratedFilterProvider();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(Container Container)
{
Container.RegisterManyForOpenGeneric(typeof(IAsyncCommandHandler<,>),
AppDomain.CurrentDomain.GetAssemblies());
Container.RegisterOpenGeneric(typeof(ITransactionCommandHandler<,>),
typeof(TransactionCommandHandlerDecorator<,>));
Container.RegisterOpenGeneric(typeof(ICommandResult<>),
typeof(CommandHandlerResult<>));
Container.Register<ICommandResolver, CommandResolver>();
Container.Register<DbContext, RemsContext>();
Container.RegisterOpenGeneric(typeof(IPager<>), typeof(PagerModel<>));
//Container.RegisterPerWebRequest<DbContext, RemsContext>();
Container.Register<UserManager<Users, Guid>, RemsUserManager>();
Container.Register<RoleManager<Roles, Guid>, RemsRoleManager>();
Container.Register<IUserStore<Users, Guid>,
UserStore<Users, Roles, Guid, UserLogins, UserRoles, Claims>>();
Container.Register<IRoleStore<Roles, Guid>, RoleStore<Roles, Guid, UserRoles>>();
Container.RegisterManyForOpenGeneric(typeof(IAsyncQueryHandler<,>),
AppDomain.CurrentDomain.GetAssemblies());
Container.RegisterManyForOpenGeneric(typeof(IAsyncQueryHandler<>),
AppDomain.CurrentDomain.GetAssemblies());
Container.RegisterManyForOpenGeneric(typeof(IQueryHandler<,>),
AppDomain.CurrentDomain.GetAssemblies());
Container.RegisterOpenGeneric(typeof(IQueryResult<>), typeof(QueryResult<>));
Container.RegisterOpenGeneric(typeof(IPaginator<>), typeof(Paginator<>));
Container.Register<IPaginator, Paginator>();
Container.RegisterOpenGeneric(typeof(IAsyncQueryHandler<>), typeof(BaseQuery<>));
Container.RegisterOpenGeneric(typeof(IQueryHandler<>), typeof(BaseQuery<>));
Container.Register<IQueryProcessor, QueryProcessor>(Lifestyle.Singleton);
Container.Register<ILog, NLogger>(Lifestyle.Singleton);
Container.RegisterInitializer<PermitAttribute>(initialize =>
{
initialize.QueryProcessor = Container.GetInstance<IQueryProcessor>();
});
Container.RegisterInitializer<BaseController>(initialize =>
{
initialize.QueryProcessor = Container.GetInstance<IQueryProcessor>();
initialize.Logger = Container.GetInstance<ILog>();
});
Container.RegisterInitializer<BaseCommandHandler>(initialize =>
{
initialize.UserManager = Container.GetInstance<RemsUserManager>();
initialize.RoleManager = Container.GetInstance<RemsRoleManager>();
initialize.RemsContext = Container.GetInstance<RemsContext>();
initialize.QueryProcessor = Container.GetInstance<IQueryProcessor>();
});
Container.RegisterInitializer<BaseHandler>(initialize =>
{
initialize.UserManager = Container.GetInstance<RemsUserManager>();
initialize.RolesManager = Container.GetInstance<RemsRoleManager>();
});
}
The exception you are seeing is caused by a verification check that has been added to version 2.6 that prevents you from calling RegisterMvcAttributeFilterProvider and RegisterMvcIntegratedFilterProvider multiple times for different container instances. The problem is described in more details here.
The solution is to make sure RegisterMvcIntegratedFilterProvider is called only once in your code for the duration of the complete app domain and since RegisterMvcAttributeFilterProvider is deprecated, prevent having any calls at all to that legacy method. So if you only have one call in there, set a break point on this line, because you might be calling the Initialize() method twice!
The new RegisterMvcIntegratedFilterProvider allows complete integration of MVC attributes in the Simple Injector pipeline which makes sure that the RegisterInitializer method is called on attributes.
Another option though is to enable explicit property injection for attributes, or to fall back on the use of passive attributes as shown here.
But one note on property injection. I noticed you make extensive use of (explicit) property injection, especially for your base classes. From a design perspective however, it's better to remove the base classes all together, because they are a design smell at least, but might become maintenance problems later on. They might violate the Single Responsibility Principle or at least hide that derived types have too many dependencies, which often means too many responsibilities. I create quite big applications myself with MVC and command handlers and query handlers and I am always able to prevent the use of base classes. If a concrete handler needs a dependency, you should simply inject it into the constructor of that type. Prevent hiding that dependency by (ab)using a base type.
There is one important detail that you should be aware about when you use the RegisterMvcIntegratedFilterProvider. MVC caches filter attributes (god knows why) and this means that such attribute is basically becoming a singleton. This implies that every dependency this filter attribute has, becomes a singleton as well. This is of course be big problem if such dependency is not registered as singleton itself; it becomes a captive dependency. Although Simple Injector contains a diagnostic warning to detect these kinds of errors, Simple Injector will be unable to detect this with attributes, because attributes are not registered in the container. Because of this, my advice is to stay away from using property injection in your attributes at all. We are considering to deprecate the RegisterMvcIntegratedFilterProvider method from the MVC integration library.
As per steven It really was calling the container registration twice .
As I got to see tht
I had called SimpleinjectorInitializer.Initialize(); method in global.asax And then the webactivator also calling the same initizer was taking toll on the simpleinjector which caused the initization to fail for a check .
The solution to that is to remove SimpleinjectorInitializer.Initialize(); from the global.asax and let webactivator do its work .

The proper way to do Dependency Injection in a Windows Client (WPF) Application

I am used to IoC/DI in web applications - mainly Ninject with MVC3. My controller is created for me, filled in with all dependencies in place, subdependencies etc.
However, things are different in a thick client application. I have to create my own objects, or I have to revert to a service locator style approach where I ask the kernel (probably through some interface, to allow for testability) to give me an object complete with dependencies.
However, I have seen several places that Service Locator has been described as an anti-pattern.
So my question is - if I want to benefit from Ninject in my thick client app, is there a better/more proper way to get all this?
Testability
Proper DI / IoC
The least amount of coupling possible
Please note I am not just talking about MVVM here and getting view models into views. This is specifically triggered by a need to provide a repository type object from the kernel, and then have entities fetched from that repository injected with functionality (the data of course comes from the database, but they also need some objects as parameters depending on the state of the world, and Ninject knows how to provide that). Can I somehow do this without leaving both repositories and entities as untestable messes?
If anything is unclear, let me know. Thanks!
EDIT JULY 14th
I am sure that the two answers provided are probably correct. However, every fiber of my body is fighting this change; Some of it is probably caused by a lack of knowledge, but there is also one concrete reason why I have trouble seeing the elegance of this way of doing things;
I did not explain this well enough in the original question, but the thing is that I am writing a library that will be used by several (4-5 at first, maybe more later) WPF client applications. These applications all operate on the same domain model etc., so keeping it all in one library is the only way to stay DRY. However, there is also the chance that customers of this system will write their own clients - and I want them to have a simple, clean library to talk to. I don't want to force them to use DI in their Composition Root (using the term like Mark Seeman in his book) - because that HUGELY complicates things in comparison to them just newing up a MyCrazySystemAdapter() and using that.
Now, the MyCrazySystemAdapter (name chosen because I know people will disagree with me here) needs to be composed by subcomponents, and put together using DI. MyCrazySystemAdapter itself shouldn't need to be injected. It is the only interface the clients needs to use to talk to the system. So a client happily should get one of those, DI happens like magic behind the scenes, and the object is composed by many different objects using best practices and principles.
I do realize that this is going to be a controversial way of wanting to do things. However, I also know the people who are going to be clients of this API. If they see that they need to learn and wire up a DI system, and create their whole object structure ahead of time in their application entry point (Composition Root), instead of newing up a single object, they will give me the middle finger and go mess with the database directly and screw things up in ways you can hardly imagine.
TL;DR: Delivering a properly structured API is too much hassle for the client. My API needs to deliver a single object - constructed behind the scenes using DI and proper practices - that they can use. The real world some times trumps the desire to build everything backwards in order to stay true to patterns and practices.
I suggest to have a look at MVVM frameworks like Caliburn. They provide integration with IoC containers.
Basically, you should build up the complete application in your app.xaml. If some parts need to be created later because you do not yet know everything to create them at startup then inject a factory either as interface (see below) or Func (see Does Ninject support Func (auto generated factory)?) into the class that needs to create this instance. Both will be supported natively in the next Ninject release.
e.g.
public interface IFooFactory { IFoo CreateFoo(); }
public class FooFactory : IFooFactory
{
private IKernel kernel;
FooFactory(IKernel kernel)
{
this.kernel = kernel;
}
public IFoo CreateFoo()
{
this.kernel.Get<IFoo>();
}
}
Note that the factory implementation belongs logically to the container configuration and not to the implementation of your business classes.
I don't know anything about WPF or MVVM, but your question is basically about how to get stuff out of the container without using a Service Locator (or the container directly) all over the place, right?
If yes, I can show you an example.
The point is that you use a factory instead, which uses the container internally. This way, you are actually using the container in one place only.
Note: I will use an example with WinForms and not tied to a specific container (because, as I said, I don't know WPF...and I use Castle Windsor instead of NInject), but since your basic question is not specificaly tied to WPF/NInject, it should be easy for you to "port" my answer to WFP/NInject.
The factory looks like this:
public class Factory : IFactory
{
private readonly IContainer container;
public Factory(IContainer container)
{
this.container = container;
}
public T GetStuff<T>()
{
return (T)container.Resolve<T>();
}
}
The main form of your app gets this factory via constructor injection:
public partial class MainForm : Form
{
private readonly IFactory factory;
public MainForm(IFactory factory)
{
this.factory = factory;
InitializeComponent(); // or whatever needs to be done in a WPF form
}
}
The container is initialized when the app starts, and the main form is resolved (so it gets the factory via constructor injection).
static class Program
{
static void Main()
{
var container = new Container();
container.Register<MainForm>();
container.Register<IFactory, Factory>();
container.Register<IYourRepository, YourRepository>();
Application.Run(container.Resolve<MainForm>());
}
}
Now the main form can use the factory to get stuff like your repository out of the container:
var repo = this.factory.GetStuff<IYourRepository>();
repo.DoStuff();
If you have more forms and want to use the factory from there as well, you just need to inject the factory into these forms like into the main form, register the additional forms on startup as well and open them from the main form with the factory.
Is this what you wanted to know?
EDIT:
Ruben, of course you're right. My mistake.
The whole stuff in my answer was an old example that I had lying around somewhere, but I was in a hurry when I posted my answer and didn't read the context of my old example carefully enough.
My old example included having a main form, from which you can open any other form of the application. That's what the factory was for, so you don't have to inject every other form via constructor injection into the main form.
Instead, you can use the factory to open any new form:
var form = this.factory.GetStuff<IAnotherForm>();
form.Show();
Of course you don't need the factory just to get the repository from a form, as long as the repository is passed to the form via constructor injection.
If your app consists of only a few forms, you don't need the factory at all, you can just pass the forms via constructor injection as well:
public partial class MainForm : Form
{
private readonly IAnotherForm form;
// pass AnotherForm via constructor injection
public MainForm(IAnotherForm form)
{
this.form = form;
InitializeComponent(); // or whatever needs to be done in a WPF form
}
// open AnotherForm
private void Button1_Click(object sender, EventArgs e)
{
this.form.Show();
}
}
public partial class AnotherForm : Form
{
private readonly IRepository repo;
// pass the repository via constructor injection
public AnotherForm(IRepository repo)
{
this.repo= repo;
InitializeComponent(); // or whatever needs to be done in a WPF form
// use the repository
this.repo.DoStuff();
}
}

CastleWindsor filling the class fields too

I am a beginner using castle windsor; and kinda introduced to it with Apress Pro Mvc book. In the project that I am working at; I use castlewindsor controller factory instead of mvc controller factory; so i can have parametrized constructors and i can inject the dependencies.
Is there a way to tell the windsorcontroller factory to inject the values to the properties of the controller class without going through constructor?
The reason I want to do this is because I have Logging dependency; Emailler Dependency; Database Dependency; Theme Engine dEpendency; and I dont want to use this many parameters parameter in the constructor.
By default, when Windsor resolves a service implementation, it will populate all properties with public setters that it can satisfy.
However, take notice that sometime it does make sense to put the dependency resolving in the constructor, for that fact that it guarantees that any instance will always be in a valid state. Consider Unit Testing scenario, where the person writing the test will go crazy about the need to know which dependencies should be supplied. When all dependencies goes into the c'tor, the tester will have no choice but to supply the tested instance with all the required dependencies (as stubs or mocks).
Anyway, as for your question, Windsor support C'tor and property injection by default
Castle Windsor will automatically fill any properties with public setters that it knows how to fill.
This means if you have a class
public MyClass {
public SomeDependency {get; set;}
}
As long as the container is configured to know how to resolve SomeDependency it will attempt to resolve and inject it.
Sometimes I've found this default behavior to be hassle. This facility will give you finer grained control over the process.

Using Dependency Injection frameworks for classes with many dependencies

I have been looking at various dependency injection frameworks for .NET as I feel the project I am working on would greatly benefit from it. While I think I have a good grasp of the capabilities of these frameworks, I am still a little unclear on how best to introduce them into a large system. Most demos (understandably) tend to be of quite simple classes that have one or two dependencies.
I have three questions...
First, how do you deal with those common but uninteresting dependencies, e.g. ILog, IApplicationSettings, IPermissions, IAudit. It seems overkill for every class to have these as parameters in their constructor. Would it be better to use a static instance of the DI container to get these when they are needed?
MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)
// ... versus ...
ILog log = DIContainer.Get<ILog>();
Second, how do you approach dependencies that might be used, but may be expensive to create. Example - a class might have a dependency on an ICDBurner interface but not want the concrete implementation to be created unless the CD Burning feature was actually used. Do you pass in interfaces to factories (e.g. ICDBurnerFactory) in the constructor, or do you again go with some static way of getting directly to the DI Container and ask for it at the point it is needed?
Third, suppose you have a large Windows Forms application, in which the top level GUI component (e.g. MainForm) is the parent of potentially hundreds of sub-panels or modal forms, each of which may have several dependencies. Does this mean that MainForm should be set up to have as dependencies the superset of all the dependencies of its children? And if you did so, wouldn't this end up creating a huge self-inflating monster that constructs every single class it could ever need the moment you create MainForm, wasting time and memory in the process?
Well, while you can do this as described in other answers I believe there is more important thing to be answered regarding your example and that is that you are probably violating SRP principle with class having many dependencies.
What I would consider in your example is breaking up the class in couple of more coherent classes with focused concerns and thus the number of their dependencies would fall down.
Nikola's law of SRP and DI
"Any class having more than 3
dependencies should be questioned for
SRP violation"
(To avoid lengthy answer, I posted in detail my answers on IoC and SRP blog post)
First: Add the simple dependencies to your constructor as needed. There is no need to add every type to every constructor, just add the ones you need. Need another one, just expand the constructor. Performance should not be a big thing as most of these types are likely to be singletons so already created after the first call. Do not use a static DI Container to create other objects. Instead add the DI Container to itself so it can resolve itself as a dependency. So something like this (assuming Unity for the moment)
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUnityContainer>(container);
This way you can just add a dependency on IUnityContainer and use that to create expensive or seldom needed objects. The main advantage is that it is much easier when unit testing as there are no static dependencies.
Second: No need to pass in a factory class. Using the technique above you can use the DI container itself to create expensive objects when needed.
Three: Add the DI container and the light singleton dependencies to the main form and create the rest through the DI container as needed. Takes a little more code but as you said the startup cost and memory consumption of the mainform would go through the roof if you create everything at startup time.
First:
You could inject these objects, when needed, as members instead of in the constructor. That way you don't have to make changes to the constructor as your usage changes, and you also don't need to use a static.
Second:
Pass in some sort of builder or factory.
Third:
Any class should only have those dependencies that it itself requires. Subclasses should be injected with their own specific dependencies.
I have a similar case related to the "expensive to create and might be used", where in my own IoC implementation, I'm adding automagic support for factory services.
Basically, instead of this:
public SomeService(ICDBurner burner)
{
}
you would do this:
public SomeService(IServiceFactory<ICDBurner> burnerFactory)
{
}
ICDBurner burner = burnerFactory.Create();
This has two advantages:
Behind the scenes, the service container that resolved your service is also used to resolve the burner, if and when it is requested
This alleviates the concerns I've seen before in this kind of case where the typical way would be to inject the service container itself as a parameter to your service, basically saying "This service requires other services, but I'm not going to easily tell you which ones"
The factory object is rather easy to make, and solves a lot of problems.
Here's my factory class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LVK.IoC.Interfaces;
using System.Diagnostics;
namespace LVK.IoC
{
/// <summary>
/// This class is used to implement <see cref="IServiceFactory{T}"/> for all
/// services automatically.
/// </summary>
[DebuggerDisplay("AutoServiceFactory (Type={typeof(T)}, Policy={Policy})")]
internal class AutoServiceFactory<T> : ServiceBase, IServiceFactory<T>
{
#region Private Fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly String _Policy;
#endregion
#region Construction & Destruction
/// <summary>
/// Initializes a new instance of the <see cref="AutoServiceFactory<T>"/> class.
/// </summary>
/// <param name="serviceContainer">The service container involved.</param>
/// <param name="policy">The policy to use when resolving the service.</param>
/// <exception cref="ArgumentNullException"><paramref name="serviceContainer"/> is <c>null</c>.</exception>
public AutoServiceFactory(IServiceContainer serviceContainer, String policy)
: base(serviceContainer)
{
_Policy = policy;
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoServiceFactory<T>"/> class.
/// </summary>
/// <param name="serviceContainer">The service container involved.</param>
/// <exception cref="ArgumentNullException"><paramref name="serviceContainer"/> is <c>null</c>.</exception>
public AutoServiceFactory(IServiceContainer serviceContainer)
: this(serviceContainer, null)
{
// Do nothing here
}
#endregion
#region Public Properties
/// <summary>
/// Gets the policy that will be used when the service is resolved.
/// </summary>
public String Policy
{
get
{
return _Policy;
}
}
#endregion
#region IServiceFactory<T> Members
/// <summary>
/// Constructs a new service of the correct type and returns it.
/// </summary>
/// <returns>The created service.</returns>
public IService<T> Create()
{
return MyServiceContainer.Resolve<T>(_Policy);
}
#endregion
}
}
Basically, when I build the service container from my service container builder class, all service registrations are automatically given another co-service, implementing IServiceFactory for that service, unless the programmer has explicitly registered on him/her-self for that service. The above service is then used, with one parameter specifying the policy (which can be null if policies aren't used).
This allows me to do this:
var builder = new ServiceContainerBuilder();
builder.Register<ISomeService>()
.From.ConcreteType<SomeService>();
using (var container = builder.Build())
{
using (var factory = container.Resolve<IServiceFactory<ISomeService>>())
{
using (var service = factory.Instance.Create())
{
service.Instance.DoSomethingAwesomeHere();
}
}
}
Of course, a more typical use would be with your CD Burner object. In the above code I would resolve the service instead of course, but it's an illustration of what happens.
So with your cd burner service instead:
var builder = new ServiceContainerBuilder();
builder.Register<ICDBurner>()
.From.ConcreteType<CDBurner>();
builder.Register<ISomeService>()
.From.ConcreteType<SomeService>(); // constructor used in the top of answer
using (var container = builder.Build())
{
using (var service = container.Resolve<ISomeService>())
{
service.Instance.DoSomethingHere();
}
}
inside the service, you could now have a service, a factory service, which knows how to resolve your cd burner service upon request. This is useful for the following reasons:
You might want to resolve more than one service at the same time (burn two discs simultaneously?)
You might not need it, and it could be costly to create, so you only resolve it if needed
You might need to resolve, dispose, resolve, dispose, multiple times, instead of hoping/trying to clean up an existing service instance
You're also flagging in your constructor which services you need and which ones you might need
Here's two at the same time:
using (var service1 = container.Resolve<ISomeService>())
using (var service2 = container.Resolve<ISomeService>())
{
service1.Instance.DoSomethingHere();
service2.Instance.DoSomethingHere();
}
Here's two after each other, not reusing the same service:
using (var service = container.Resolve<ISomeService>())
{
service.Instance.DoSomethingHere();
}
using (var service = container.Resolve<ISomeService>())
{
service.Instance.DoSomethingElseHere();
}
First:
You might approach it by creating a container to hold your "uninteresting" dependencies (ILog, ICache, IApplicationSettings, etc), and use constructor injection to inject that, then internal to the constructor, hydrate the fields of the service from container.Resolve() ? I'm not sure I'd like that, but, well, it's a possibility.
Alternatively, you might like to use the new IServiceLocator common interface (http://blogs.msdn.com/gblock/archive/2008/10/02/iservicelocator-a-step-toward-ioc-container-service-locator-detente.aspx) instead of injecting the dependencies?
Second:
You could use setter injection for the optional/on-demand dependencies? I think I would go for injecting factories and new up from there on-demand.
To partially answer my first question, I've just found a blog post by Jeremy Miller, showing how Structure Map and setter injection can be used to auto-populate public properties of your objects. He uses ILogger as an example:
var container = new Container(r =>
{
r.FillAllPropertiesOfType<ILogger>().TheDefault.Is
.ConstructedBy(context => new Logger(context.ParentType));
});
This means that any classes with an ILogger property, e.g.:
public class ClassWithLogger
{
public ILogger Logger { get; set; }
}
public class ClassWithLogger2
{
public ILogger Logger { get; set; }
}
will have their Logger property automatically set up when constructed:
container.GetInstance<ClassWithLogger>();

Resources