1

我有一個使用StructureMap的Web API應用程序,並且我已經介紹了最新版本的NServiceBus(版本6)來引入pub/sub以更改數據。如何配置NServiceBus 6以在Web API中使用現有的StructureMap容器​​?

問題是我似乎無法獲得現有的容器注入到StructureMapBuilder中。

的結構如下:

public class WebApiRegistry : Registry 
{ 
    public WebApiRegistry() 
    { 
     For(typeof(IRepository<>)).Use(typeof(Repository<>)); 
     For(typeof(IProcessor<>)).Use(typeof(PassThroughProcessor<>)); 
     For<IUnitOfWork>().Use<UnitOfWork>(); 
     For<ILog>().Use(container => LogManager.GetLogger("My.WebApi")); 
    } 
} 

此註冊表,然後在在Global.asax的Aplication_Start方法註冊:

GlobalConfiguration.Configuration.UseStructureMap<WebApiRegistry>(); 

的問題是在這裏,在相同的方法:

var endpointConfiguration = new EndpointConfiguration("My.WebApi.Sender"); 
endpointConfiguration.UseTransport<MsmqTransport>(); 
endpointConfiguration.UseSerialization<NServiceBus.JsonSerializer>(); 
endpointConfiguration.UsePersistence<InMemoryPersistence>(); 
endpointConfiguration.UseContainer<StructureMapBuilder>(); //No idea how to get the existing container in here??? 
endpointConfiguration.SendOnly(); 

我想不出如何用NServiceBus註冊現有的容器。

我有一個使用AutoFac的例子,這可能是因爲它是默認的NServiceBus的DI框架,但我很想讓它與StructureMap一起工作。

任何想法?

+0

這應該工作。 https://docs.particular.net/samples/containers/structuremap/ – Nkosi

+0

感謝您的迴應,但不幸的是,這不起作用:'沒有默認實例註冊,不能自動確定的類型'NServiceBus.IMessageSession'是當我調用配置爲發送的控制器操作時的結果。此外,必須重複Global.asax中的WebApiRegistry代碼是我想避免的。 –

+0

提供檢查答案 – Nkosi

回答

2

手動創建容器,並將其用於兩臺Web API和NServiceBus

var registry = new WebApiRegistry(); 
var container = new Container(registry); 

//Register StructureMap with GlobalConfiguration 
GlobalConfiguration.Configuration.UseStructureMap(container); 


var endpointConfiguration = new EndpointConfiguration("My.WebApi.Sender"); 

//...other code removed for brevity 

//Configuring NServiceBus to use the container 
endpointConfiguration.UseContainer<StructureMapBuilder>(
    customizations: customizations => { 
     customizations.ExistingContainer(container); 
    }); 

//...other code removed for brevity 

var endpointInstance = await Endpoint.Start(endpointConfiguration); 
// OR Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult(); 
IMessageSession messageSession = endpointInstance as IMessageSession; 

// Now, change the container configuration to know how to resolve IMessageSession 
container.Configure(x => x.For<IMessageSession>().Use(messageSession)); 
+1

@BillyRayValentine看看這個https://stackoverflow.com/a/40622554/5233410和這個https://stackoverflow.com/a/40348435/5233410 – Nkosi

+0

@BillyRayValentine看起來像'NServiceBus.IMessageSession'未默認向容器註冊,並且僅在啓動端點後纔可用。所以需要找到一種方法讓它進入容器 – Nkosi

+1

@BillyRayValentine我想我明白了。檢查更新的答案。 – Nkosi

相關問題