开发者

asp.net c# reflection, creating more instance then expected

开发者 https://www.devze.com 2023-04-09 02:58 出处:网络
I have a helper method here in class. It returns all the instances of a given interface in all the ap开发者_开发技巧p domain dlls.

I have a helper method here in class. It returns all the instances of a given interface in all the ap开发者_开发技巧p domain dlls.

public static class Helper
{
  public static List<T> GetOfType<T> ()
  {
    var t =  from asm in AppDomain.CurrentDomain.GetAssemblies()
                  from type in asm.GetTypes()
                  where !type.IsInterface && !type.IsAbstract && typeof(T).IsAssignableFrom(type)
                  select (T)Activator.CreateInstance(type);
   return t.List();
 }
}

Edit

Now say i have interface

IUserContent
{
  string URL {get;set;}

 }

and a implementation say PhotoContent

public class PhotoContent
{
     public string URL {get;set]}
}

now when i say

var c = Helper.GetOfType<IUserContent>();

It gives me 9 instances of IUserContent all pointing to photocontent

That is the problem. I couldnt understand what is the reason.

Can someone help here.

Regards Parminder


The first thing to do is to get the full name:

foreach(var obj in c) {
    Console.WriteLine(c.GetType().AssemblyQualifiedName);
}

that gives you the full type-names (including assemblies) of the types invovled. My guess would be that the type has been accidentally declared in multiple assembles or namespaces.


You have two from clauses in your LINQ query. Could it be that this causes the results to be returned multiple times? I would try using SelectMany instead:

var t = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(type => !type.IsInterface && !type.IsAbstract && typeof(T).IsAssignableFrom(type))
    .Select(type => (T)Activator.CreateInstance(type));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号