amplifier
amplifier

Reputation: 1833

Dependency injection by type names

For my example I use Autofac (it's not necessary):

var r = builder.RegisterType<Helper>().As<IHelper>(); // usual using

What I'd like to do is to be able to register types somehow like:

string name1 = "Helper";

string name2 = "IHelper";

var r = builder.RegisterType<GetTypeFromName(name1)>().As<GetTypeFromName(name2)>();

Is it possible to do with reflection magic?

Upvotes: 1

Views: 715

Answers (3)

John Wu
John Wu

Reputation: 52290

If you're able to get te Type object for the type you want to register, you can pass it to Autofac using a different overload of the RegisterType method, like so:

var type = Assembly.LoadFrom(path).GetType(typeName);
builder.RegisterType(type);

Upvotes: 1

Igor
Igor

Reputation: 62268

You would have to create a mechanism that would "figure out" which concrete types you want to register and how to expose them (the As part in AutoFac). Here is a sample of how you can register using System.Type so the missing part is obtaining the System.Types yourself.

// get your Type(s)
Type concreteType = typeof(Helper);
Type asType = typeof(IHelper);

// Autofac registration call
builder.RegisterType(concreteType).As(asType);

As you can see in the above code you should call the non-generic version of the RegisterType and As methods. (The generic versions really just call down to these anyways).

Upvotes: 2

Mark Adelsberger
Mark Adelsberger

Reputation: 45799

Generally to resolve a type name you would need to provide more information than just the class name. So I guess the answer is "not exactly".

The method for mapping a string to a type is Type.GetType, which is documented here: https://learn.microsoft.com/en-us/dotnet/api/system.type.gettype?view=netframework-4.7.2

As you can see, in a vacuum we can't say that "Helper" or "IHelper" would be sufficient. You probably could get by with a namespace-qualified class name. (The reason why Helper works in the "hard-coded" syntax, of course, is that the compiler can take advantage of using statements in deciding what Helper should mean. That option doesn't work when GetType is trying to understand a string at runtime.)

If you can provide a custom resolver, maybe you can make it work exactly as you describe.

Upvotes: 1

Related Questions