Does the Funq IoC container support resolving all registrations for a type? Something like either of these:
IEnumerable<IFoo> foos = container.Resolve<IEnumerable<IFoo>>();
IEnumerable<IFoo> foos = container.ResolveAll<IFoo>();
Funq does not have a ResolveAll method, but you can simply register an IEnumerable<IFoo> and resolve it with Resolve<IEnumerable<IFoo>>() as you show in your question.
In general however, it is better not to request the container for collections, but use composites instead. This way you can simply inject an IFoo as a dependency, instead of forcing consumers of that dependency to iterate the list. Instead you embed the code that loops the list of IFoo instances inside the composite. This keeps your code DRY and doesn't force you to go through the (possible) dozens of foreach (var foo in foos) statements scattered throughout the application, when a change has to be made in the way the items are iterated. Or let me put it in an other way: it is not the responsibility of a consumer to know how to iterate all IFoos.
Here is an example of an IFoo Composite:
// A composite is something that implements an interface
// (in this case IFoo) and wraps a list of items of that
// same interface.
public class FooComposite : IFoo
{
private readonly IEnumerable<IFoo> foos;
public FooComposite(params IFoo[] foos)
{
this.foos = foos;
}
void IFoo.FooThatThing(IBar bar)
{
foreach (var foo in this.foos)
{
foo.FooThatThing(bar);
}
}
}
Instead of registering an IEnumerable<IFoo>, you can register a CompositeFoo as IFoo:
container.Register<IFoo>(c => new CompositeFoo(
new Foo1(), new Foo2(), new Foo3()));
Now you can let the container inject that CompositeFoo in consumers that take an IFoo argument, which makes them unaware that they are in fact dealing with a list of IFoo elements.
UPDATE:
Using this composite pattern, you can easily control the lifetime of each IFoo item. It's just a matter of calling back into the container. With Funq,it would look like this:
container.Register<IFoo>(c => new CompositeFoo(
c.Resolve<Foo1>(),
c.Resolve<Foo2>(),
c.Resolve<Foo3>()));
This way you can register Foo1 as singleton and Foo2 as transient for instance. When the CompositeFoo is reused however, Foo2 will not really be transient, but it's just a matter of changing the CompositeFoo and its registration to solve this problem. For instance, you can change your CompositeFoo to the following:
public class FooComposite : IFoo
{
private readonly Func<IFoo>[] fooFactories;
public FooComposite(params Func<IFoo>[] fooFactories)
{
this.fooFactories = fooFactories;
}
void IFoo.FooThatThing(IBar bar)
{
foreach (var fooFactory in this.fooFactories)
{
var foo = fooFactory();
foo.FooThatThing(bar);
}
}
}
Now instead of injecting some IFoos into the constructor, we can inject some lambdas in it:
container.Register<IFoo>(c => new CompositeFoo(
() => c.Resolve<Foo1>(),
() => c.Resolve<Foo2>(),
() => c.Resolve<Foo3>()));
This will ensure that every time CompositeFoo's FooThatThing is called, the container is queried for new IFoo instances. This allows FooThatThing to be called multiple times by the same consumer, and even allows CompositeFoo to be registered as singleton.
This advice holds for all containers and Dependency Injection in general, and is not specific to the use of Funq.
For those of you who want the anti-pattern, simply because you might not want to implement a factory pattern, here is my version based on last 3.9.71.
Only downside is that it adds a bit more memory and you have to register the services through registerOneOfMany(). you might want to change the bag for a list with a lock (for faster reads) and switch to servicstack funq's default: ReuseScope.Default
public static class FunqExtensions
{
private static readonly ConcurrentDictionary<Type,ConcurrentBag<string>> registrations = new ConcurrentDictionary<Type, ConcurrentBag<string>>();
public static void RegisterOneOfMany<TBase, TImplementation>(this Container container, string name = null, ReuseScope scope = ReuseScope.None) where TImplementation : TBase
{
if (name == null)
name = Guid.NewGuid().ToString();
var funq = Container.GenerateAutoWireFn<TImplementation>();
container.Register<TBase>(name, (c) => funq(c))
.ReusedWithin(scope);
registrations.GetOrAdd(typeof(TBase), type => new ConcurrentBag<string>()).Add(name);
}
public static IEnumerable<T> ResolveAll<T>(this Container container)
{
ConcurrentBag<string> result;
if (registrations.TryGetValue(typeof(T), out result))
{
var rator = result.GetEnumerator();
while (rator.MoveNext())
{
yield return container.ResolveNamed<T>(rator.Current);
}
}
}
}
Related
I have an algorithm to run, like this:
public interface IAlgorithm
{
void Run();
}
It depends on the IContainer interface that looks like this:
public interface IContainer
{
int Size();
}
The implemention of this interface needs some data gotten from UI
public class Container : IContainer
{
private readonly List<int> _data;
public Container(IEnumerable<int> data)
{
_data = new List<int>(data);
}
public int Size()
{
return _data.Count;
}
}
Then the implementation of IAlgorithm might look like this:
public class Algorithm : IAlgorithm
{
private readonly IContainer _container;
public Algorithm(IContainer container)
{
_container = container;
}
public void Run()
{
Console.WriteLine(_container.Size());
}
}
I want to implement this interface so that it's injectible via NInject (so I can use it as a constructor parameter for a ViewModel).
public interface IAlgorithmFactory
{
IAlgorithm Create(IEnumerable<int> data);
}
The problem is: I need to be able to get the right instance of IContainer from the Kernel during the Algorithm construction. In the real-world situations the dependency graph of the algorithm is quite big and there is not one thing that needs to be created from the data, but 3 and these things are further dependencies of some other things.
My solution is that all classes that needs to be created from the data have the method called Initialize. The caller must initilize these serives before using other methods. That sounds like a bad practice.
In fact, the real code that I'm talking about can be seen here. Right now everything is injected as Singleton.
Is there some other way to inject those things via NInject?
Note: I already asked this question here, from a design point of view. I think this is the better place to get the answer specifically about an NInject solution.
Just by using Ninject configuration, you can do it in this way:
var kernel = new StandardKernel();
kernel.Bind<IContainer>()
.To<Container>()
.WithConstructorArgument("data",
ctx => ctx.Request.ParentContext.Parameters
.Single(x => x.Name == "data")
.GetValue(ctx, null));
kernel.Bind<IAlgorithm>().To<Algorithm>();
kernel.Bind<IAlgorithmFactory>().ToFactory();
var factory = kernel.Get<IAlgorithmFactory>();
var algorithm = factory.Create(new List<int>() { 1 });
Here the data parmeter is taken from the factory method parameter and passed down to the Container constructor.
I'm used to the approach when it is the object that creates another object (either directly or through factories, builders, etc) - is the one that "owns" it, thus manages its lifetime.
This idea works fine in almost every case.
But sometimes the one that creates an object simply cannot manage it, for instance in the builder design pattern implementation:
IFoo BuildFoo()
{
var dep = new Dep();
return new Foo(dep);
}
So, here the builder cannot manage the lifetime of the dep object since:
it does not have a reference to it;
it does not know when it is safe to Dispose it.
The naive solution would be to make Foo : IDisposable and let it manage the Dep passed to its constructor.
But then another dilemma arises:
using (var dep = new Dep())
{
using (var foo = new Foo(dep))
{
// (1) do something with foo
}
// (2) !!! do something with dep !!!
}
The code above becomes unsafe: at the point (2) it's not safe to use dep since it is already Disposed by foo.
And there is nothing syntactically that can denote, whose responsibility it is to manage the lifetime of an object.
So the question: what would be a general solution for that?
In this case, I wouldn't worry about it. I'm going to get shot to pieces here, I imagine, but "builders", "factories" etc are all places where I think it's okay to create an object and hand off it's disposal to the thing that asked for it.
There is a rule though that the builder/factory must only be creating the object, and not doing anything with it.
Of course, if you're newing-up objects using the new keyword, then you're coupling yourself to that implementation (even if it's indirectly via a factory class). You might want instead to consider dependency injection, depending on what the created objects are for, in which case a DI container would create the objects and dispose them for you at the correct time, based on their configured lifestyle.
very naive implementation
void Main()
{
using (var builder = new Builder())
{
var foo = builder.Create();
// do smtg
}
}
public class Foo
{
public Foo(Dep instance)
{
}
}
public class Dep : IDisposable
{
public void Dispose()
{
Console.WriteLine($"{this.GetType().Name} disposed!");
}
}
public class Builder : IDisposable
{
private List<IDisposable> _disposables = new List<System.IDisposable>();
public Foo Create()
{
var dep = new Dep();
_disposables.Add(dep);
var foo = new Foo(dep);
return foo;
}
public void Dispose()
{
foreach(var d in _disposables)
d.Dispose();
Console.WriteLine($"{this.GetType().Name} disposed!");
}
}
If something owns IDisposable, then it should implement IDisposable.
And, ofcourse, this is very naive impl, just as sample.
What about you let Foo call the builder to instantiate Dep and use it whenever it needs to. This way Foo manages the lifetime of Dep without the client of Foo having to worry about it.
I have the following code:
_container = new UnityContainer();
_container.RegisterType<IDownloader, Downloader>();
_container.RegisterType<INewObject, NewObject>();
_container.RegisterType<SearchViewModel>();
SearchViewModel class with constructor injection:
class SearchViewModel
{
private readonly Func<IDownloader> _downloaderFactory;
private readonly INewObject _newObject;
private IDownloader _downloader;
public SearchViewModel(Func<IDownloader> downloaderFactory, INewObject newObject)
{
_downloaderFactory = downloaderFactory;
_newObject = newObject;
}
}
The question: How to register SearchViewModel that has Fun<> as parameter?
_container.RegisterType<SearchViewModel>(new InjectionConstructor(DownloaderFactory()));
The code above works only without INewObject.
The goal: Resolve factory with InjectionConstructor and resolve INewObject, INewObject2, INewObject3 automatically (like without parameters: RegisterType<SearchViewModel>()).
Is it possible? Maybe alternates?
I have solved the problem:
_container.RegisterType<Func<IDownloader>>(new InjectionFactory(i =>
new Func<IDownloader> (() => _container.Resolve<IDownloader>())));
_container.RegisterType<SearchViewModel>();
new Func is a key, because before I tried:
_container.RegisterType<Func<IDownloader>>(new InjectionFactory(i =>
_container.Resolve<IDownloader>()));
Also the better way to use IDownloaderFactory instead of Func<IDownloader> downloaderFactory. IDownloaderFactory can encapsulate the delegate.
Also I think that using a delegate as dependency inside factory is better solution than broken Composition Root.
The generally accepted pattern to use here is to declare an abstract factory and make it slightly more explicit:
public interface IDownloaderFactory
{
IDownloader Create();
}
Then you create a class to represent the factory that simply uses the container again to resolve instances:
public class DownloaderFactory : IDownloaderFactory
{
private UnityContainer _Container;
public DownloaderFactory(UnityContainer container)
{
this._Container = container;
}
public IDownloader Create()
{
return this._Container.Resolve<IDownloader>();
}
}
Using this approach is more explicit and plays more nicely with the containers, also it still keeps the container away from your application and business logic, now you just need a small adjustment to your SearchViewModel class:
class SearchViewModel
{
private readonly IDownloaderFactory _downloaderFactory;
private readonly INewObject _newObject;
public SearchViewModel(IDownloaderFactory downloaderFactory, INewObject newObject)
{
_downloaderFactory = downloaderFactory;
_newObject = newObject;
Console.WriteLine(downloaderFactory.Create().GetHashCode());
Console.WriteLine(downloaderFactory.Create().GetHashCode());
}
}
Now you can see it just works and creates new instances each time.
Setting up the container would look like this:
var container = new UnityContainer();
container.RegisterType<IDownloader, Downloader>();
container.RegisterType<INewObject, NewObject>();
container.RegisterType<IDownloaderFactory, DownloaderFactory>();
container.RegisterType<SearchViewModel>();
container.RegisterInstance(container);
var model = container.Resolve<SearchViewModel>();
Notice that you need to register the instance of the container you are working with so that the factory gets the same instance either using this method or a ThreadLocal instancing or something.
Note:
also just be wary of the fact that using the Func approach or using the container to resolve the downloader may cause undesired effects in your client. For instance if the container is set up by default to be transient to objects of Downloader then a new instance is created each time. Chaning the lifetime on the container may result in the client to get the same instance each time. In such a case it is better to manually construct the downloader object in the factory and use the container only for the arguments of downloader.
This is a fairly straight forward decorator pattern scenario, with the complication that the decorated type has a constructor parameter that is dependent on the type into which it is being injected.
I have an interface like this:
interface IThing
{
void Do();
}
And an implementation like this:
class RealThing : IThing
{
public RealThing(string configuration)
{
... implementation ...
}
public void Do()
{
... implementation ...
}
}
And a decorator like this:
class DecoratingThing : IThing
{
IThing _innerThing;
public DecoratingThing(IThing thing)
{
_innerThing = thing;
}
public void Do()
{
_innerThing.Do();
}
}
Finally, I have some types that require an IThing, called Depender1, Depender2 etc..
class DependerX()
{
public DependerX(IThing thing)
{
... implementation ...
}
}
I want to configure an IOC container to resolve instances of DependerX such that they are injected with RealThing decorated with a DecoratingThing. Important: Each DependerX type requires a different value of configuration to be passed to the constructor of its RealThing, say "ConfigX" in each case. e.g. The work done by the IoC container might be:
new Depender1(new DecoratingThing(new RealThing("Config1")));
new Depender2(new DecoratingThing(new RealThing("Config2")));
... and so on.
In Unity, this seems quite clunky to configure as I have to mix in the decorator with the decorated:
container.RegisterType<IThing, DecoratingThing>("ConfigX",
new InjectionFactory(container => new DecoratingThing(new RealThing("ConfigX"));
container.RegisterType<DependerX>(
new InjectionConstructor(new ResolvedParameter<IThing>("ConfigX");
And repeat, violating DRY nicely, for each DependerX.
What I'd like to do is remove the need to embed the construction of RealThing in the construction of DecoratingThing in each named registration of IThing - and declare the decoration just once. This is so, for example, that if the decoration needs to change in future, it's easier to reconfigure. The best I came up with is this helper method for registration:
void RegisterDepender<TDepender>(IUnityContainer container, string config)
{
container.RegisterType<TDepender>(new InjectionConstructor(
new ResolvedParameter<IThing>(config)));
container.RegisterType<IThing, DecoratingThing>(config,
new InjectionFactory(c => new DecoratingThing(new RealThing(config))));
}
This removes repetition at least, but I still have to embed the construction of the RealThing inside the DecoratingThing - this means I can't vary their lifetimes independently for example. I can't register IThing again to do this because I've used up my registration of that interface for the name. If I want to do that I have to introduce another set of named instances like so:
void RegisterDepender<TDepender>(IUnityContainer container, string config)
{
string realConfig = "Real" + config;
container.RegisterType<TDepender>(new InjectionConstructor(
new ResolvedParameter<IThing>(config)));
container.RegisterType<IThing, DecoratingThing>(config,
new InjectionFactory(c => new DecoratingThing(
container.Resolve<IThing>(realConfig))));
container.RegisterType<IThing, RealThing>(realConfig,
new ContainerControlledLifetimeManager(),
new InjectionConstructor(config));
}
Is this really the best option? It feels complex and potentially hard for those that will come after to grok. Do other IoC containers have a compelling way to cover this scenario? Since the pattern for how injection works is repeated for each DependerX, is there a way to only use a named instance at the top (DependerX) level?
Any other comments?
The class design itself seems reasonable. Here's a convention-based container configuration that basically does this:
public class MyConventions : UnityContainerExtension
{
protected override void Initialize()
{
var dependers = from t in typeof(IThing).Assembly.GetExportedTypes()
where t.Name.StartsWith("Depender")
select t;
foreach (var t in dependers)
{
var number = t.Name.TrimStart("Depender".ToArray());
var realName = "Real" + number;
var decoName = "Deco" + number;
var config = "Config" + number;
this.Container.RegisterType<IThing, RealThing>(realName,
new InjectionConstructor(config));
this.Container.RegisterType<IThing, DecoratingThing>(decoName,
new InjectionConstructor(
new ResolvedParameter<IThing>(realName)));
this.Container.RegisterType(t,
new InjectionConstructor(
new ResolvedParameter<IThing>(decoName)));
}
}
}
This configuration will automatically add all classes that match the above predicate, so once you've set it up, you can just add more classes (like Depender4 or Depender5) without revisiting the container configuration at all.
The above configuration satisfies these unit tests:
[Fact]
public void ContainerCorrectlyResolvesDepender1()
{
var container = new UnityContainer().AddNewExtension<MyConventions>();
var actual = container.Resolve<Depender1>();
var deco = Assert.IsAssignableFrom<DecoratingThing>(actual.Thing);
var thing = Assert.IsAssignableFrom<RealThing>(deco.Thing);
Assert.Equal("Config1", thing.Configuration);
}
[Fact]
public void ContainerCorrectlyResolvesDepender2()
{
var container = new UnityContainer().AddNewExtension<MyConventions>();
var actual = container.Resolve<Depender2>();
var deco = Assert.IsAssignableFrom<DecoratingThing>(actual.Thing);
var thing = Assert.IsAssignableFrom<RealThing>(deco.Thing);
Assert.Equal("Config2", thing.Configuration);
}
[Fact]
public void ContainerCorrectlyResolvesDepender3()
{
var container = new UnityContainer().AddNewExtension<MyConventions>();
var actual = container.Resolve<Depender3>();
var deco = Assert.IsAssignableFrom<DecoratingThing>(actual.Thing);
var thing = Assert.IsAssignableFrom<RealThing>(deco.Thing);
Assert.Equal("Config3", thing.Configuration);
}
Have you ever thought about basing your decorators on the Unity Interception functionality? Then it would be really easy to say "intercept the calls to IThing using this Interceptor" just once.
container.AddNewExtension<Interception>();
container.RegisterType<IThing>(new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<DecoratingThingBehavior>());
and then it would be "inject this IThing into this and that Depender"
container.RegisterType<Depender1>(new InjectionConstructor(new ResolvedParameter<IThing>("myNameForThing")));
I am testing a class that has two dependencies on IFoo. Both instances of IFoo should be MOCK objects so that I can VerifyExpectations on each. Each instance is created and managed by the RhinoMocksMockingKernel.
I think that the mocking kernel is getting confused about which instance it should be verifying.
I also think that I may be confused about the proper way to setup RhinoMocksMockingKernel for this case.
I do know that I can use dep1.AssertWasCalled... vs. dep1.VerifyAllExpectations().
Here is the sample code.
public interface IFoo
{
void DoX();
void DoY();
}
public class SubjectUnderTest
{
private readonly IFoo dep1;
private readonly IFoo dep2;
public void DoWork()
{
dep1.DoX();
dep2.DoY();
}
public SubjectUnderTest(IFoo dep1, IFoo dep2)
{
this.dep2 = dep2;
this.dep1 = dep1;
}
}
[TestFixture]
public class Tests
{
[Test]
public void DoWork_DoesX_And_DoesY()
{
var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
var dep1 = kernel.Get<IFoo>();
var dep2 = kernel.Get<IFoo>();
// tried this binding but it doesnt seem to work
kernel.Bind<SubjectUnderTest>()
.ToSelf()
.WithConstructorArgument("dep1", dep1)
.WithConstructorArgument("dep2", dep2);
var sut = kernel.Get<SubjectUnderTest>();
dep1.Expect(it => it.DoX());
dep2.Expect(it => it.DoY());
sut.DoWork();
dep1.VerifyAllExpectations();
dep2.VerifyAllExpectations();
}
}
As ryber said, you should not really be using your IOC container in your tests that way. However, I'll still answer the question in case you have this issue in normal code. You can use the Named attribute as shown in this other stackoverflow question: How To Use Ninject Named Bindings With DependencyResolver and PropertyInjection
In that example, the Named attribute is above of the function but you can also put it right next to your arguments to specify which one should be used. E.g.
public void SubjectUnderTest([Named("Alpha")] IFoo alpha, [Named("Beta")]) {
...
}
And the bindings should be registered as such described in this post: How To Use Ninject Named Bindings With DependencyResolver and PropertyInjection
You can also use a the ToMethod binding to just manually create your object.
So I found a way to verify the expections on dep1 and dep2, but I was not able to use the AutoMockingKernel to manage and create dep1 and dep1.
Here is the code that I came up with.
It's pretty lame answer. It seems like I should be able to use the mocking kernel to Get two seperate instances of IFoo...
Here is my current code... lameo...
[TestFixture]
public class Tests
{
[Test]
public void DoWork_DoesX_And_DoesY()
{
var kernel = new Ninject.MockingKernel.RhinoMock.RhinoMocksMockingKernel();
var dep1 = MockRepository.GenerateMock<IFoo>();
var dep2 = MockRepository.GenerateMock<IFoo>();
kernel.Bind<IFoo>().ToMethod((ctx) => dep1).When((ctx) => ctx.Target.Name.StartsWith("dep1"));
kernel.Bind<IFoo>().ToMethod((ctx) => dep2).When((ctx) => ctx.Target.Name.StartsWith("dep2"));
var sut = kernel.Get<SubjectUnderTest>();
dep1.Expect(it => it.DoX());
dep2.Expect(it => it.DoY());
sut.DoWork();
dep1.VerifyAllExpectations();
dep2.VerifyAllExpectations();
}
}