BAD_SEED
BAD_SEED

Reputation: 5056

Retrieve type from a String

I have this class:

namespace Ns1.Ns2.Domain
{
    public class Process
    {
        private IIndex IndexBuilderConcr { get; set; }

        public Processo(String processType) {
            IndexBuilderConcr = new UnityContainer().RegisterType<IIndex, *>().Resolve<IIndex>();
        }
    }
}

Here I have a constructor that takes a String. This string represent a type that should replace the * sign at line 8. I have googled araound but with no luck.

Upvotes: 2

Views: 112

Answers (3)

James S
James S

Reputation: 3588

The method for this is the static Type.GetType(fullyQualifiedTypeNameString) You need to know the namespace for this to be possible, but the assembly name is inferred if it is in the currently executing assembly.

So if the namespace is known, but not passed in you could do

string fullyQualifiedTypeName = "MyNamespace." + processType;
Type resolvedProcessType = Type.GetType(fullyQualifiedTypeName);

However you can't just pass this Type object as a typeparameter, because that's not how generics work. Generics require the type to be known at compile time - so passing a Type object as a Typeparameter is not a valid way of saying that is the required Type.

To get round this reflection can be used instead. There is another answer by dav_i which demonstrates this.

Upvotes: 0

BAD_SEED
BAD_SEED

Reputation: 5056

The dav_i answer is pretty correct, indeed, since I'm using Unity the best way to achieve this is named mapping:

namespace Ns1.Ns2.Domain
{
    public class Process
    {
        private IIndex IndexBuilderConcr { get; set; }

        public Processo(String processType) {
            IndexBuilderConcr = new UnityContainer().Resolve<IIndex>(processType);
        }
    }
}

and then inside the App.config:

<container>
  <register type="IIndex" mapTo="IndexAImpl" name="A"/>
  <register type="IIndex" mapTo="IndexBImpl" name="B"/>
</container>

where name attributes is the processType string.

Upvotes: 0

dav_i
dav_i

Reputation: 28097

What you'll need to do is get the type in the way James S suggests, but you'll need to pass that value into the method in a slightly different way as calling Method<resolvedProcessType> is invalid:

var type = Type.GetType("Some.Name.Space." + processType);

var methodInfo = typeof(UnityContainer).GetMethod("RegisterType");

// this method's argument is params Type[] so just keep adding commas
// for each <,,,>
var method = methodInfo.MakeGenericMethod(IIndex, type);

// we supply null as the second argument because the method has no parameters
unityContainer = (UnityContainer)method.Invoke(unityContainer, null);

unityContainer.Resolve<IIndex>();

Upvotes: 2

Related Questions