假设我有以下服务合同和两个具体实现:
[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...
}
}
这些属性带有 a 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 注入具体实现?看来我应该做以下事情:
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 中的绑定不会更改。有没有办法根据配置文件中的值更改绑定?我在这里做错了吗?