StructureMap IRegistrationConvention to register non default naming convention?

前端 未结 2 934
不思量自难忘°
不思量自难忘° 2021-01-02 14:30

I currently have a bunch of repositories like so

IMyRepository
IAnotherRepository

They all inherit from IRepository (if this helps)

How can I get

相关标签:
2条回答
  • 2021-01-02 14:48

    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 讨论(0)
  • 2021-01-02 15:08

    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>();
                });
    
    0 讨论(0)
提交回复
热议问题