Initialize implementation type with context arguments #363

jaimetotal opened this Issue Dec 26, 2016 · 3 comments


None yet

2 participants

jaimetotal commented Dec 26, 2016 edited

Given the following logger implementation:

public class AppLogger : IAppLogger { public AppLogger(string className) {...} }

How can I register the implementation and provide the class name of the class that receives this dependency?

In the previous version, the method RegisterWithContext() was available but it was deprecated for the RegisterConditional() but doesn't seem to work as it doesn't allow to initialize a class, AFAIK.


You can use the RegisterConditional method for this, but Simple Injector requires static type information for this to work. So you will have to create a generic derivative as follows:

sealed class AppLogger<T> : AppLogger { public AppLogger() : base(typeof(T).FullName) { } }

Using RegisterConditional you can do the registration as follows:

    c => typeof(AppLogger<>).MakeGenericType(c.Consumer.ImplementationType),
    c => true);

See this for more information.


Thanks for the quick reply.

Regarding your solution, it does the job but feels like I'm affecting a class due to the framework.

Wasn't the RegisterWithContext() a better fit for this purpose?

dotnetjunkie commented Dec 26, 2016 edited

it does the job but feels like I'm affecting a class due to the framework.

This solution doesn't affect your framework or application, since this generic AppLogger<T> will just be part of your Composition Root. That class is an adapter that allows you to wire everything with Simple Injector. So you can see it as a Simple Injector specific class, which is fine, since everything in your Composition Root is specific to Simple Injector.

Wasn't the RegisterWithContext() a better fit for this purpose?

RegisterWithContext was littered with problems. That's why it was never part of the library itself, and that's why it has been expelled from the documentation since the introduction of v3. Core problem with RegisterWithContext was that it completely blinded Simple Injector therefore disallowed doing analysis and diagnostics on your behalf. It also allowed making runtime decisions during object composition, which makes object graph composition fragile and disallowed Simple Injector to make the registration with anything but Transient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment