Castle Windsor - Nested runtime dependencies - inversion-of-control

I am using Castle Windosr container. I want to be able to specify some constructor dependencies at runtime which you can obviously do by using a Resolve overload that takes a dictionary, all good and fine. However if I want to specify runtime dependency for a dependency of the root then I'm lost, at the moment I've worked around by explicitly creating each and bedding it in. Essentially its a decorator scenario and I want to get an instance of the decarator whilst providing a dependency at runtime for the object under decoration. Any ideas? I'd rather not have to do what I'm doing below and I'd rather not have the decarator constructor populate the object underneath since there will be times when the dependencies are not the same.
public static IActivity GetActivityFromIoC(string key, Message message, Audit audit)
{
IActivity activity = IoC.Resolve<IActivity>(key, new Dictionary<
string, object>(){
{ "message", message }
});
IActivity auditingActivity = IoC.Resolve<IActivity>("auditing.activity", new Dictionary<
string, object>(){
{ "activity", activity },
{ "message", message },
{ "audit", audit }
});
return auditingActivity;
}

You probably could handle this by writing your own ISubDependencyResolver implementation that would do that for you.
The container alone does not allow that, and most likely it never will.
Why? The short answer is - by doing that you make assumptions about you component's dependency dependencies, which is a no-no and container is all about removing this kind of knowledge from the caller.

Related

Resolving to parent interface during constructor injection

This involves autofac and c#. I have an interface derived from a parent interface:
public interface IJ4JLogger<out TCalling>
{
}
public interface IJ4JSmsLogger<out TCalling> : IJ4JLogger<TCalling>
{
}
Certain classes depend on being supplied an instance of the parent interface during construction:
public FileHistoryConfiguration( IJ4JLogger<FileHistoryConfiguration> histLogger, IJ4JLogger<FileHistoryService> svcLogger )
{
}
But if I register the type like this with autofac:
builder.RegisterGeneric( typeof(J4JSmsLogger<>) )
.As(typeof(IJ4JSmsLogger<>))
.SingleInstance();
where J4JSmsLogger<> is a class implementing IJ4JSmsLogger<>, then this call fails with an error that it can't find anything registered to provide an IJ4JLogger<> interface:
_fhConfig = _svcProvider.GetRequiredService<IFileHistoryConfiguration>();
I can work around the problem by changing the As<> clause in the registration of J4JSmsLogger<> to treat it as a IJ4JLogger<> instance, and then cast the result of resolving that interface to IJ4JSmsLogger<> whenever I need the extra capabilities of the child interface.
But I don't understand why I have to do that. Is there an additional step I need to take during registration of the types with autofac so that objects implementing the child interface will satisfy a need for the parent interface?
Cleaner Workaround
Reading more about autofac I learned something new: you can define as many As<>() clauses (including AsSelf()) as you want. So changing my autofac configuration to:
builder.RegisterGeneric( typeof(J4JSmsLogger<>) )
.As(typeof(IJ4JSmsLogger<>))
.As(typeof(IJ4JLogger<>))
.SingleInstance();
provides a cleaner solution than constantly casting resolved instances.
I'm not going to submit it as an answer, though, because I am curious why autofac doesn't do this kind of downcasting automatically, and whether any other DI frameworks do.
Autofac won't cast to base types for you like that. It generally assumes wiring is exact. You could run into some real problems if it didn't, like if someone has a constructor like...
public class BadTimes
{
public BadTimes(object input) { }
}
Which object does it put in there? Everything casts down to object.
However, you could always register it as both types and call it a day:
builder.RegisterGeneric(typeof(J4JSmsLogger<>))
.As(typeof(IJ4JSmsLogger<>))
.As(typeof(IJ4JLogger<>))
.SingleInstance();

Resolution of ILifetimeService fails in autofac 4.6.2

We're refactoring an older system to use DI. Sadly, some of the "core" components that are used all over everywhere have injection unfriendly constructors (descriptions, for example), so we have to use ServiceLocator to create them. Refactoring them is very impractical at this time.
We're trying to create the unfriendly classes by injecting ILifetimeScope into the appropriate place, but are getting the following exception:
No constructors on type 'Autofac.Core.Registration.ScopeRestrictedRegistry' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.
If I cheat and use the "Update" method on the ContainerBuilder and then register the container as the LifetimeScope, the resolution works successfully, however, given that Update is obsolete, it's not something I want to do.
Can anyone help?
Edit: I'm not doing anything special. Build up is standard:
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
this.Container = builder.Build();
builder = new ContainerBuilder();
builder.RegisterInstance(this.Container);
builder.RegisterInstance(this.Container).As<ILifetimeScope>();
builder.Update(this.Container);
Without these lines
builder = new ContainerBuilder();
builder.RegisterInstance(this.Container);
builder.RegisterInstance(this.Container).As<ILifetimeScope>();
builder.Update(this.Container);
any class with an ILifetimeScope dependency fails with the error above.
public class MyClass : IMyClass
{
public MyClass(ILifetimeScope scope)
{
...
}
}
I'm actually thinking that this is a bug in the Autofac Framework, so I'm hoping that someone from the team will be able to tell me more.
ILifetimeScope is supposed to automatically be available.

Detecting the cause of a circular dependency in Unity

Is it possible to configure Unity to either detect a circular reference or to intercept the type resolver to display some debugging information?
Example
Here are a couple of interfaces and classes which are dependent upon each other
public interface IThing1 { }
public class Thing1 : IThing1
{
private IThing2 _thing2;
public Thing1(IThing2 thing2)
{
_thing2 = thing2;
}
}
public interface IThing2 { }
public class Thing2 : IThing2
{
private IThing1 _thing1;
public Thing2(IThing1 thing1)
{
_thing1 = thing1;
}
}
Castle Windsor
If these two types are configured in Castle Windsor it will throw an exception and provide some debug information to find the circular reference:
Castle.MicroKernel.CircularDependencyException: Dependency cycle has been detected when trying to resolve component 'CircularIoC.Thing1'.
The resolution tree that resulted in the cycle is the following:
Component 'CircularIoC.Thing1' resolved as dependency of
component 'CircularIoC.Thing2' resolved as dependency of
component 'CircularIoC.Thing1' which is the root component being resolved.
Unity
If Unity is configured to resolve these types like so
private static void ResolveWithUnity()
{
var container = new UnityContainer();
container.RegisterType<IThing1, Thing1>();
container.RegisterType<IThing2, Thing2>();
var thing = container.Resolve<IThing1>();
container.Dispose();
}
The call to container.Resolve<> will cause a StackOverflowException.
This is the documented behaviour but it would be nice to have some more useful information. Is there any customisation that will provide more information about the circular reference?
Alternatively is there any way to hook in to the type resolver process to emit some debugging information? I am thinking of decorating the main type resolver to output the name of the type being resolved. This will provide some feedback and a pointer to dependency that is causing the circular reference.
While I know that changing to a different IoC would solve the problem, this is not unfortunately an option.
Unity sadly doesn't support this (incredibly important) feature.
If you are willing to put your back into it, you can implement a smart decorator using some elbow grease.
What you will need is to override all Registration methods and build and update a data structure for the dependencies (dependency graph).
Then write a method that preforms DFS to detect a circular dependency, you can either use it as a finalizer for the registration process, that will detect pre-resolving if circular dependencies are possible, or use it per resolve for the specific type requested.
As you can see, it's a lot of work...
Another option, is just to wrap up with a decorator the resolve methods and catch the StackOverflowException, analyze it to make sure it resulted from the resolving process, and build a proper circular dependency exception.

Avoiding the service locator with inversion of control while dynamically creating objects

I have a WPF application based on MVVM with Caliburn.Micro and Ninject. I have a root viewmodel called ShellViewModel. It has a couple of dependencies (injected via constructor) which are configured in Caliburn's Bootstrapper. So far so good.
Somewhere down the line, there is a MenuViewModel with a couple of buttons, that in turn open other viewmodels with their own dependencies. These viewmodels are not created during creation of the root object, but I still want to inject dependencies into them from my IoC container.
I've read this question on service locator vs dependency injection and I understand the points being made.
I'm under the impression however that my MenuViewModel needs to be able to access my IoC container in order the properly inject the viewmodels that are being made dynamically..which is something I'm trying to avoid. Is there another way?
Yes, I believe you can do something a bit better.
Consider that if there was no on-demand requirement then obviously you could make those viewmodels be dependencies of MenuViewModel and so on up the chain until you get to the root of the object graph (the ShellViewModel) and the container would wire everything up.
You can put a "firewall" in the object graph by substituting something that can construct the dependencies of MenuViewModel for the dependencies themselves. The container is the obvious choice for this job, and IMHO from a practical standpoint this is a good enough solution even if it's not as pure.
But you can also substitute a special-purpose factory instead of the container; this factory would take a dependency on the container and provide read-only properties for the real dependencies of MenuViewModel. Accessing the properties would result in having the container resolve the objects and returning them (accessor methods would also work instead of properties; what's more appropriate is another discussion entirely, so just use whatever you think is better).
It may look like that you haven't really changed the status quo, but the situation is not the same it would be if MenuViewModel took a direct dependency on the container. In that case you would have no idea what the real dependencies of MenuViewModel are by looking at its public interface, while now you would see that there's a dependency on something like
interface IMenuViewModelDependencyFactory
{
public RealDependencyA { get; }
public RealDependencyB { get; }
}
which is much more informative. And if you look at the public interface of the concrete MenuViewModelDependencyFactory things are also much better:
class MenuViewModelDependencyFactory : IMenuViewModelDependencyFactory
{
private Container container;
public MenuViewModelDependencyFactory(Container container) { ... }
public RealDependencyA { get { ... } }
public RealDependencyB { get { ... } }
}
There should be no confusion over what MenuViewModelDependencyFactory intends to do with the container here because it's so very highly specialized.

ExportLifetimeContext<T>

Why does the ExportLifetimeContext<T> exist? What is it for? And why is it necessary to call Dispose on this objec at all? Do I really need to bother calling it? It doesn't feel very managed if I have to spend time thinking about resource managment, it doesn't feel very managed to me.
Is this dispose in anyway tied to the Value property? Is there a specific problem with just going CreateExport().Value?
When you ask an ExportFactory to create a new object, MEF might actually also create dependencies, and the dependencies of those dependencies, etcetera. Many objects might be created because you asked for a single object.
Some of these extra objects might be IDisposable, and the container is responsible for disposing those when they are no longer necessary.
To signal to the container that you are done using your object, you call ExportLifetimeContext<T>.Dispose(). The MEF container will then take care of disposing the requested object and its dependencies if necessary. If you don't do this, MEF will keep references to these objects forever, waiting for a signal that it can dispose them.
In Autofac 2, a very similar mechanism exists. Instead of ExportFactory, they use Func<Owned<T>> and you need to call Owned<T>.Dispose() to clean up.
edit: The MEF documentation has a Parts lifetime section where it is described in which cases exactly the container keeps references to exports. It does not yet mention ExportLifetimeContext.Dispose but I imagine this is similar to CompositionContainer.ReleaseExport.
edit: note that ExportFactory is intended for cases where you have a clearly defined lifetime. If this is not the case (or you know that clean-up is never necessary), then you should create your own factory implementation. Of course, it is then your responsibility to make sure that nothing IDisposable is created, since it would be impossible to clean it up properly.
Here is an example of a custom factory import/export using Func<T>.
[Export(typeof(ISomeInterface))]
public class SomeClass
{
private readonly Func<Foo> fooFactory;
[ImportingConstructor]
public SomeClass(Func<Foo> fooFactory)
{
this.fooFactory = fooFactory;
}
public void DoStuff()
{
Foo newFoo = fooFactory();
...
}
}
public class FooFactory
{
[Export(typeof(Func<Foo>))]
public void CreateFoo()
{
...
}
}