Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap Auto registration for generic types using Scan

I've got an interface:

IRepository<T> where T : IEntity

while im knocking up my UI im using some fake repository implementations that just return any old data.

They look like this:

public class FakeClientRepository : IRepository<Client>

At the moment im doing this:

ForRequestedType<IRepository<Client>>()
   .TheDefaultIsConcreteType<FakeRepositories.FakeClientRepository>();

but loads of times for all my IEntities. Is it possible to use Scan to auto register all my fake repositories for its respective IRepository?

Edit: this is as far as I got, but i get errors saying the requested type isnt registered :(

Scan(x =>
{
    x.TheCallingAssembly();
    x.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>();
    x.AddAllTypesOf(typeof(IRepository<>));
    x.WithDefaultConventions();
});

Thanks

Andrew

like image 990
Andrew Bullock Avatar asked Feb 05 '09 17:02

Andrew Bullock


People also ask

Which of the following option is used in automatic types of registration in order to scan an assembly and automatically register its types by convention?

Use Autofac as an IoC container API Web API project with the types you will want to inject. Autofac also has a feature to scan assemblies and register types by name conventions.

What is StructureMap?

StructureMap is a feature rich IoC tool with support for interception, object lifecycles and intelligent disposal patterns, open generic types, modular registrations, conventional registration, custom policies, and all the injection pattern support you would expect in a modern . Net IoC container.


1 Answers

There is an easier way to do this. Please see this blog posting for details: Advanced StructureMap: connecting implementations to open generic types

public class HandlerRegistry : Registry
{
    public HandlerRegistry()
    {
        Scan(cfg =>
        {
            cfg.TheCallingAssembly();
            cfg.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>();
            cfg.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
        });
    }
}

Doing it this way avoids having to create your own ITypeScanner or conventions.

like image 105
JD Courtoy Avatar answered Oct 25 '22 15:10

JD Courtoy