2012-03-02 46 views
0

如何註冊封閉類型以便使用HybridHttpOrThreadLocalScoped生命週期創建通用實例?使用StructureMap的掃描器註冊封閉類型

我的課:

public interface IBaseService 
{ 
} 

public interface IAccountService 
{ 
    void Save(Account entry); 
    Account GetById(string id); 
    List<Account> GetList(); 
    void Delete(string id); 
    bool Exists(string id); 
} 

public interface IClientService 
{ 
    void Save(Client entry); 
    Client GetById(string id); 
    List<Client> GetList(); 
    void Delete(string id); 
    bool Exists(string id); 
} 

public class AccountService : IBaseService, IAccountService 
{ 
    Some code for managing accounts 
} 

public class ClientService : IBaseService, IClientService 
{ 
    Some code for managing clients 
} 

依賴解析器:

public StructureMapContainer(IContainer container) 
    { 
     _container = container; 

     _container.Configure(x => x.Scan(y => 
     { 
      y.AssembliesFromApplicationBaseDirectory(); 
      y.WithDefaultConventions(); 
      y.LookForRegistries(); 
      y.ConnectImplementationsToTypesClosing(typeof(IService<>)) 
       .OnAddedPluginTypes(t => t.HybridHttpOrThreadLocalScoped()); 
     })); 

    } 

什麼是在解析器的語法自動創建IBaseService的實例?使用ConnectImplementationsToTypesClosing僅適用於開放泛型。我甚至需要使用旋轉變壓器嗎?有沒有更好的方式來註冊類型?

現在,我這是怎麼amhandling註冊它們:

container.Configure(x => 
     { 
      x.For<IClientService>() 
       .HybridHttpOrThreadLocalScoped() 
       .Use(new ClientService()); 

      x.For<IEmailAddressService>() 
       .HybridHttpOrThreadLocalScoped() 
       .Use(new EmailAddressService()); 

      x.For<IAccountService>() 
       .HybridHttpOrThreadLocalScoped() 
       .Use(new AccountService()); 
     }); 

回答

0

喜歡的東西:

Scan(y => 
    { 
     y.AssemblyContainingType<IService>(); 
     y.Assembly(Assembly.GetExecutingAssembly().FullName); 
     y.With(new ServiceScanner()); 
    }); 

然後,你需要的Customscanner:

/// <summary> 
/// Custom scanner to create Service types based on custom convention 
/// In this case any type that implements IService and follows the 
/// naming convention of "Name"Service. 
/// </summary> 
public class ServiceScanner : IRegistrationConvention 
{ 
    public void Process(Type type, StructureMap.Configuration.DSL.Registry registry) 
    { 
     if (type.BaseType == null) return; 

     if (type.GetInterface(typeof(IService).Name) != null) 
     { 
      var name = type.Name; 
      var newtype = type.GetInterface(string.Format("I{0}", name)); 

      registry 
       .For<IService>() 
       .AddInstances(y => y.Instance(new ConfiguredInstance(type).Named(name))) 
       .HybridHttpOrThreadLocalScoped(); 

      registry.For(newtype) 
       .HybridHttpOrThreadLocalScoped().Use(c => c.GetInstance<IService>(name)); 
     } 
    } 
} 
+0

我想試試。謝謝! – rboarman 2012-03-03 16:33:10