StructureMap automatically registers descendant classes

I have a base class Repository <T>. In a specific project, I have several use cases for this base class. eg

PersonRepository : Repository<T>
EmployerRepository : Repository<T>

      

I am currently registering each of these repositories in the StructureMap ServiceRegistry class. eg:

ForRequestedType<Repository<Person>>()
  .TheDefaultIsConcreteType<PersonRepository>();
ForRequestedType<Repository<Employer>>()
  .TheDefaultIsConcreteType<EmployerRepository>();

      

It sucks because every time I add a repository I have to remember it. This is one more step.

Is there a way that I could search for the project / assembly where the PersonRepository is located and log everything that inherits from Repository <T>?

+2


source to share


1 answer


EDIT . I just downloaded a new StructureMap construct from a CI server project . Now you need what you need and there is no need to use the user agreement:

public class RepositoryRegistry : Registry
{
    public RepositoryRegistry()
    {
        Scan(assemblyScanner =>
             {
                 assemblyScanner.AssemblyContainingType<PersonRepository>();
                 assemblyScanner.AddAllTypesOf(typeof (IRepository<>));
                 assemblyScanner.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
             });
    }
}

      

This is my original solution:



This is a good starting point, but it probably needs to be clarified:

public class RepositoryRegistry : Registry
{
    public RepositoryRegistry()
    {
        Scan(assemblyScanner =>
             {
                 assemblyScanner.AssemblyContainingType<PersonRepository>();
                 assemblyScanner.AddAllTypesOf(typeof (IRepository<>));
                 assemblyScanner.With<RepositoryConvention>();
             });
    }
}

public class RepositoryConvention : ITypeScanner
{
    public void Process(Type type, PluginGraph graph)
    {
        var selectedInterface =
            (from @interface in type.GetInterfaces()
            where @interface.IsGenericType &&
                  @interface.GetGenericTypeDefinition()
                      .IsAssignableFrom(typeof (IRepository<>))
            select @interface).SingleOrDefault();

        if(selectedInterface != null)
            graph.Configure(registry =>
                 registry.ForRequestedType(selectedInterface)
                    .TheDefaultIsConcreteType(type)
             );
    }
}

      

+3


source







All Articles