开发者

StructureMap IRegistrationConvention to register non default naming convention?

I currently have a bunch of repositories like so

IMyRepository

IAnotherRepository

They all inherit from IRepository (if this helps)

How can I get structuremap to use an IRegistryConvention scanner to register my concrete types which are named

SqlMyRepository

SqlAnotherRepo开发者_StackOverflow中文版sitory


I had read that article but it didn't give me quite what I needed. The AddAllTypesOf registered all the concrete types against the IRepositoryInterface but instead I require that each concrete type is registered against the interface with equivilent naming. ie.

For<IMyRepository>().Use<SqlMyRepository>();

Also I need to create some named instances for test repositories.

For<IMyRepository>().Use<TestMyRepository>().Named("Test");

Here's what I came up with which appears to work as I need it.

public class SqlRepositoryConvention : StructureMap.Graph.IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        // only interested in non abstract concrete types that have a matching named interface and start with Sql           
        if (type.IsAbstract || !type.IsClass || type.GetInterface(type.Name.Replace("Sql", "I")) == null)
            return;

        // Get interface and register (can use AddType overload method to create named types
        Type interfaceType = type.GetInterface(type.Name.Replace("Sql","I"));
        registry.AddType(interfaceType, type);
    }
}

And implemented as follows

Scan(cfg =>
            {
                cfg.TheCallingAssembly();
                cfg.Convention<SqlRepositoryConvention>();
            });


Check out http://codebetter.com/blogs/jeremy.miller/archive/2009/01/20/create-your-own-auto-registration-convention-with-structuremap.aspx

In particular, this part

        container = new Container(x =>

        {

            x.Scan(o =>

            {

                o.TheCallingAssembly();
                o.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", ""));

            });

        });

So for you, I think something like this should work

        container = new Container(x =>

        {

            x.Scan(o =>

            {

                o.TheCallingAssembly();
                o.AddAllTypesOf<IRepository>().NameBy(type => type.Name.Replace("I", "Sql"));

            });

        });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜