zirus
zirus

Reputation: 313

How to instantiate objects given a Class name and a base Namespace

I'm deserializing DTO objects in run time. And i've used the code below to instantiate objects given a namespace and a type name

public class SimpleDtoSpawner : DtoSpawner{
    private readonly Assembly assembly;
    private readonly string nameSpace;

    public SimpleDtoSpawner(){
        assembly = Assembly.GetAssembly(typeof (GenericDTO));

        //NOTE: the type 'GenericDTO' is located in the Api namespace
        nameSpace = typeof (GenericDTO).Namespace ; 

    }

    public GenericDTO New(string type){
        return Activator.CreateInstance(
            assembly.FullName, 
            string.Format("{0}.{1}", nameSpace, type)
            ).Unwrap() as GenericDTO;
    }
}

This implementation worked for me, when all Commands and Events were in the Api namespace.
But after i separated them into two namespaces: Api.Command and Api.Event, i need to instantiate them without an exact namespace reference.

Upvotes: 0

Views: 252

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499800

You could do something like this:

public class SimpleDtoSpawner : DtoSpawner{
    private readonly Dictionary<string, Type> types;

    public SimpleDtoSpawner() {
        Assembly assembly = Assembly.GetAssembly(typeof (GenericDTO));
        string baseNamespace = typeof (GenericDTO).Namespace ; 
        types = assembly.GetTypes()
                        .Where(t => t.Namespace.StartsWith(baseNamespace))
                        .ToDictionary(t => t.Name);
    }

    public GenericDTO New(string type) {
        return (GenericDTO) Activator.CreateInstance(types[name]).Unwrap();
    }
}

That will go bang when creating the dictionary if you have more than one type under the same "base namespace" with the same simple name. You might also want to change the filter to check whether the type is assignable to GenericDTO too.

Upvotes: 1

Related Questions