gpt4 book ai didi

c# - 在配置文件中动态注入(inject)基于关闭值的 WCF ServiceContract 的具体实现

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:56 24 4
gpt4 key购买 nike

假设我有以下服务契约和两个具体实现:

[OperationContract]
public interface ISearchService {
public ICollection<string> Search(string text);
}

[SearchServiceBehaviour]
public class SolrSearchService : ISearchService {
public ICollection<string> Search(string text) {
// Implementation...
}
}

[SearchServiceBehaviour]
public class SqlSearchService : ISearchService {
public ICollection<string> Search(string text) {
// Implementation...
}
}

这些都带有 ServiceBehavior 属性,因此我可以在服务运行时根据配置文件创建实例:

public class SearchServiceBehaviour : Attribute, IServiceBehavior {
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) {
foreach (var item in serviceHostBase.ChannelDispatchers) {
var dispatcher = item as ChannelDispatcher;

if (dispatcher != null) {
dispatcher.Endpoints.ToList().ForEach(e => {
e.DispatchRuntime.InstanceProvider = new SearchServiceInstanceProvider();
});
}
}
}
}

public class SearchServiceInstanceProvider : IInstanceProvider {
public object GetInstance(InstanceContext instanceContext, Message message) {
// Should cache and only do this at an interval.
ConfigurationManager.RefreshSection("appSettings");
var index = ConfigurationManager.AppSettings["UseSolr"] as string;

bool UseSolr;
bool.TryParse(index, out UseSolr);

if (UseSolr)
return new IndexedSearchService();
else
return new SearchService();
}
}

我的问题是如何根据配置文件中不断变化的值使用 Ninject 注入(inject)具体实现?看来我应该做以下事情:

public class SearchServiceModule : NinjectModule {
private bool UseSolr;

public SearchServiceModule() {
// Should cache and only do this at an interval.
ConfigurationManager.RefreshSection("appSettings");
var index = ConfigurationManager.AppSettings["UseSolr"] as string;

bool.TryParse(index, out UseSolr);
}

public override Load() {
if (UseSolr)
Bind<ISearchService>().To<SolrSearchService>();
else
Bind<ISearchService>().To<SqlSearchService>();
}
}

然后在 InstanceProvider 中:

public object GetInstance(InstanceContext instanceContext, Message message) {
return _kernel.Get<ISearchService>();
}

但是,在我更改配置文件中的值后,Ninject 中的绑定(bind)不会更改。有没有办法根据配置文件中的值更改绑定(bind)?我在这里做错了什么吗?

最佳答案

您的模块没有像您预期的那样运行,因为有一个字段和一个同名的局部变量。

另请参阅条件绑定(bind)。 .When()

关于c# - 在配置文件中动态注入(inject)基于关闭值的 WCF ServiceContract 的具体实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10115468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com