简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM