Unity 2.0 registering generic types via XML

后端 未结 3 1763
灰色年华
灰色年华 2020-12-09 12:48

I am trying to register a generic type in a config file for Unity 2.0 but can\'t seem to get it right. I have been referring to the MS documentation here : http://msdn.micro

相关标签:
3条回答
  • 2020-12-09 13:03

    I think you need to add `1, as the examples here on MSDN would suggest:

    type="X.Services.Interfaces.IRepository`1[[X.Domain.Entities.Blog, X.Domain]], X.Services"
    
    0 讨论(0)
  • 2020-12-09 13:08

    MSDN is NOT wrong. We specifically added some shortcut parsing rules so that you don't have to enter all the `'s and square brackets in most cases.

    I slapped together an example that looks mostly like yours:

    public interface IRepository<T> where T: class
    {
    
    }
    
    public class GenericRepository<T> : IRepository<T> where T : class
    {
    
    }
    
    public class BlogRepository : GenericRepository<Blog>
    {
    
    }
    
    public class Blog
    {
    
    }
    

    My XML config looks like this:

      <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
        <namespace name="UnityConfigExample"/>
        <assembly name="UnityConfigExample"/>
    
        <container>
          <register type="IRepository[]" mapTo="GenericRepository[]" />
          <register type="IRepository[Blog]" mapTo="BlogRepository" />
        </container>
      </unity>
    

    and it just works.

    Were you by any chance trying to use an alias for IRepository instead of the namespace / assembly search? I got the following to work as well using aliases:

      <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
        <alias alias="IRepository" type="UnityConfigExample.IRepository`1, UnityConfigExample" />
        <alias alias="GenericRepository" type="UnityConfigExample.GenericRepository`1, UnityConfigExample"/>
        <alias alias="BlogRepository" type="UnityConfigExample.BlogRepository, UnityConfigExample"/>
        <alias alias="Blog" type="UnityConfigExample.BlogRepository, UnityConfigExample"/>
    
        <container>
          <register type="IRepository[]" mapTo="GenericRepository[]" />
          <register type="IRepository[Blog]" mapTo="BlogRepository" />
        </container>
      </unity>
    

    When you specify the type for an alias, you must use the CLR type syntax. Everywhere else you can use the generic shortcut syntax.

    0 讨论(0)
  • 2020-12-09 13:20

    you're missing a ` character before [[ (below Esc on my keyboard)

    0 讨论(0)
提交回复
热议问题