2012-06-20 52 views

回答

1

與作者協商後,這裏是需要的代碼:

UContainer 
    .ConfigureAutoRegistration() 
    .LoadAssemblyFrom(Assembly.GetEntryAssembly().Location) 
    .ExcludeSystemAssemblies() 
    .Include(If.ImplementsITypeName, Then.Register()) 
    .Include(
     type => type.GetInterfaces().Any(i => i.Name.StartsWith("I") && i.Name.Substring(1) == type.Name.Substring(1)), Then.Register()) 
    .Include(If.ImplementsSingleInterface, Then.Register()) 
    .ApplyAutoRegistration(); 
0

自動註冊的代碼很長時間沒有被觸及。 TecX project on codeplex包含Unity的增強配置引擎,該引擎作爲StructureMap配置的一個端口啓動。該引擎還支持註冊約定。

其中一個默認約定將類MyService註冊爲接口IMyService的實現。如果你需要一些自定義的命名約定這將是非常容易修改上面的示例

public class ImplementsIInterfaceNameConvention : IRegistrationConvention 
{ 
    public void Process(Type type, ConfigurationBuilder builder) 
    { 
    if (!type.IsConcrete()) 
    { 
     return; 
    } 
    Type pluginType = FindPluginType(type); 
    if (pluginType != null && 
     Constructor.HasConstructors(type)) 
    { 
     builder.For(pluginType).Add(type).Named(type.FullName); 
    } 
    } 
    private static Type FindPluginType(Type concreteType) 
    { 
    string interfaceName = "I" + concreteType.Name; 
    Type[] interfaces = concreteType.GetInterfaces(); 
    return Array.Find(interfaces, t => t.Name == interfaceName); 
    } 
} 

:它看起來那樣簡單。使用約定來配置你的容器會是這個樣子:

var builder = new ConfigurationBuilder(); 
builder.Scan(s => 
      { 
      s.AssembliesFromApplicationBaseDirectory(); 
      s.With(new MyCustomConvention()); 
      }); 
var container = new UnityContainer(); 
container.AddExtension(builder); 
相關問題