2013-04-11 19 views
1

我有什么似乎是比较常见的情况。我需要注入一个需要构造函数的依赖项。如何在NServiceBus中配置构造函数注入

我有一个仓库,看起来像这样:

public class ApprovalRepository : IApprovalRepository 
{ 
    private readonly MongoCollection<Approval> _collection; 

    public ApprovalRepository(MongoDatabase database) 
    { 
     this._collection = database.GetCollection<Approval>("Approvals"); 
    } 

    // ... 
} 

端点配置,看起来像这样:

public class EndpointConfig : IConfigureThisEndpoint, 
    AsA_Server, IWantCustomInitialization 
{ 
    public void Init() 
    { 
     NServiceBus.Configure.With().DefaultBuilder().JsonSerializer(); 
    } 
} 

而且看起来像这样的处理程序:

public class PlaceApprovalHandler : IHandleMessages<PlaceApproval> 
{ 
    public IApprovalRepository ApprovalRepository { get; set; } 

    public void Handle(PlaceApproval message) 
    { 
     // 
     ApprovalRepository.Save(
      new Approval 
       { 
        Id = message.Id, 
        Message = message.MessageText, 
        ProcessedOn = DateTime.UtcNow 
       }); 
    } 
} 

然后我有一个类来做自定义初始化:

public class ConfigureDependencies : IWantCustomInitialization 
{ 
    public void Init() 
    { 
     // configure Mongo 
     var client = new MongoClient("mongodb://localhost:27017/?safe=true"); 
     var server = client.GetServer(); 
     var database = server.GetDatabase("ServiceBusTest"); 

     Configure.Instance.Configurer.RegisterSingleton<IApprovalRepository>(new ApprovalRepository(database)); 
    } 
} 

结果是错误的:

2013-04-11 17:01:03,945 [Worker.13] WARN NServiceBus.Unicast.UnicastBus [(null)] <(null)> - PlaceApprovalHandler failed handling message. 
Autofac.Core.DependencyResolutionException: Circular component dependency detected: Server.PlaceApprovalHandler -> Server.ApprovalRepository -> Server.ApprovalRepository. 
    at Autofac.Core.Resolving.CircularDependencyDetector.CheckForCircularDependency(IComponentRegistration registration, Stack`1 activationStack, Int32 callDepth) in :line 0 
    at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) in :line 0 

我没那么熟悉Autofac。我也试过以下,这也有类似的结果:

Configure.Instance.Configurer.ConfigureComponent(() => new ApprovalRepository(database), DependencyLifecycle.SingleInstance) 

回答

0

在我ApprovalRepository,一些奇怪的代码已出现在,即:然后

#region Public Properties 

public IApprovalRepository Repository { get; set; } 

#endregion 

NServiceBus试图自动注入该属性。结果ApprovalRepository接受了一个IApprovalRepository。糟糕!我的错。现在解释错误:

Server.PlaceApprovalHandler -> Server.ApprovalRepository -> Server.ApprovalRepository 
0

在我看来,您尝试向处理程序注入的具体类型对于端点本身而言应该是未知的。

https://code.google.com/p/autofac/wiki/Scanning

我想通过 “选入” 选择我的类型通过把一个自定义属性的类:

[AttributeUsage(AttributeTargets.Class)] 
public class RegisterServiceAttribute : Attribute {} 

然后选择这样的类型:

builder.RegisterAssemblyTypes(assemblies) 
    .Where(t => t.GetCustomAttributes(typeof (RegisterServiceAttribute), false).Any()) 
    .AsSelf() 
    .AsImplementedInterfaces(); 

作为我做的一个例子:

public class EndpointConfig : IConfigureThisEndpoint, IWantCustomInitialization, AsA_Server, UsingTransport<SqlServer> 
{ 
    public void Init() 
    { 
     var builder = new ContainerBuilder(); 

     builder.RegisterAssemblyTypes(GetAllAssemblies()) 
      .Where(t => t.GetCustomAttributes(typeof(ProviderAttribute), false).Any()) 
      .AsSelf() 
      .AsImplementedInterfaces(); 

     Configure 
      .With() 
      .UseTransport<SqlServer>() 
      .AutofacBuilder(builder.Build()) 
      .UseNHibernateTimeoutPersister() 
      .UseNHibernateSagaPersister() 
      .UnicastBus(); 
    } 

    private static Assembly[] GetAllAssemblies() 
    { 
     var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 

     return Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFile).ToArray(); 
    } 
} 
相关问题