C# Auto-scanning factory

2019-08-06 11:10发布

问题:

I there any patterns or internal solutions for solving next problem:

i've got interface ImyInterface(or some baseClass) and Attribute myAttribute. I need a factory class, that provides me functionality for searching all types with empty constructor, inheriting ImyInterface and marked with attribute myAttribute.

I wanna search in different modes: 1) search types in current assembly 2) search types in all solution assemblies 3) search types in target library (.lib or .dll)

at result I wanna see something like this:

Some sought-for type implementation:

[myAttribute(uniqueTypeNameOrSomethingLikeThat = "SuperClass")]
public class mySomeResource:ImyInterface
{
   mySomeResource(){...}
}

Factory using:

  myResourceFactory  factory = new myResourceFactory(typeof(ImyInterface), typeof(myAttribute));

  factory.ScanThisAssembly();
  factory.ScanDirrectory("C:\\libraries");

  var atlast = (ImyInterface)factory.Create("SuperClass");

I've already wrote my own solution, but I'am in fear of "reinventing the wheel".

got any ideas/experience about this problem?

回答1:

That pattern is called Inversion of control. There are about a million dependency injection containers solving this problem, each with their own positive and negative quirks. Pick one that you like best or roll your own if none fits your needs.