我想设置我的WCF服务以使用IoC容器。 Autofac wiki中有一篇关于WCF集成的文章,但它只显示了与IIS中托管的服务的集成。
但我的服务托管在Windows服务中。
我在这里得到了一个关于开幕活动的建议 http://groups.google.com/group/autofac/browse_thread/thread/23eb7ff07d8bfa03
我遵循了建议,这是我到目前为止所得到的:
private void RunService<T>()
{
var builder = new ContainerBuilder();
builder.Register(c => new DataAccessAdapter("1")).As<IDataAccessAdapter>();
ServiceHost serviceHost = new ServiceHost(typeof(T));
serviceHost.Opening += (sender, args) => serviceHost.Description.Behaviors.Add(
new AutofacDependencyInjectionServiceBehavior(builder.Build(), typeof(T), ??? ));
serviceHost.Open();
}
AutofacDependencyInjectionServiceBehavior有一个ctor,它有3个参数。第三个是IComponentRegistration
类型,我不知道从哪里可以得到它。有什么想法吗?
提前致谢。
答案 0 :(得分:6)
我写过一篇博文,介绍如何在自托管WCF服务时使用Autofac WCF集成。
http://alexmg.com/self-hosting-wcf-services-with-the-autofac-wcf-integration/
这应该足以指出你正确的方向。我将更新Autofac wiki上的文档以包含相同的示例。
答案 1 :(得分:0)
自从Alex Meyer做出回应以来,Autofac发生了一些变化。基本上是一行代码:
//Instead of
host.Description.Behaviors.Add(new AutofacDependencyInjectionServiceBehavior(container, typeof(EchoService), registration));
//Use this
host.AddDependencyInjectionBehavior<IEchoService>(container);
来源:https://autofaccn.readthedocs.io/en/latest/integration/wcf.html#self-hosting