2
votes

I want to create types using Unity. I do not know the specific type on compile time. I create a Type instance from string using the following code:

var theType = Type.GetType( "System.Exception" );

When I try to resolve the type using the container I get an Exception as he tries to use the constructor with the most parameters:

_Container.Resolve( theType ); // <- uses a constructor with message, etc.

I know I could either configure the resolving using a config file containing something like

<register type="Exception">
    <constructor />
</register>

or by code using

container.RegisterType<Exception>(new InjectionConstructor());

The latter possibility does not work on System.Exception for obvious reasons...

Is there a possibility to tell the Resolve method to use the ()-constructor? ResolverOverride seems to help to pass parameters, but I want to use the default constructor and fail otherwise. Right know I call Activator.CreateInstance, but I would like to use Unity consistently.

Note: Exception was just used as a sample class that contains multiple constructors. As a plugin created by another developer might have too, as I have no control over the available constructors using an interface.

Edit: My idea is, that if there is a configuration in the config file Unity would use the constructor configured there. If not use the default constructor. I do not like the idea of a fallback. Try first with Unity, then use Activator

1
If you don't need to inject any dependencies and aren't tracking the objects as dependencies for other classes constructed by the container, Activator.CreateInstance seems like the correct tool for the job. - Dan Bryant
@DanBryant It does the job, that's right. I edited the question to make my concern a bit clearer. I will think about the idea to limit the plugins to require a parameterless constructor though - Sascha
Why are you using Unity to create an instance of exception? Seems a rather weird thing to do - Something having a dependency on Exception - Jamiec
@Jamiec I just placed Exception there as a sample for a class that has multiple constructors. My app creates instances of classes that all must implement a specific interface. As I cannot force an implementation to have just parameterless constructor (which might be unwanted) I used Unity for the configuration purposes. When used without configuration it should not try to create the plugin using the most precise constructor but the one that should be callable at all times. - Sascha

1 Answers

0
votes

I think you could just use

var theType = Type.GetType("some_type");
_Container.Register(theType,  new InjectionConstructor());