使用Autofac for DI进入ASP.NET应用程序中托管的WCF服务

Oli*_*ver 14 asp.net wcf dependency-injection autofac

我在使用Autofac 1.4.5将服务依赖项注入我的WCF服务时遇到了麻烦.我已阅读并遵循WcfIntegration上Autofac wiki页面,但我的调试显示我的WCF服务是由System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance()方法创建的,而不是由AutofacWebServiceHostFactory.我究竟做错了什么?

我将我的ajax.svc文件设置为与示例中的文件一样用于WebHttpBinding:

<%@ ServiceHost Language="C#" Debug="true"
    Service="Generic.Frontend.Web.Ajax, Generic.Frontend.Web"
    Factory="Autofac.Integration.Wcf.AutofacWebServiceHostFactory,
             Autofac.Integration.Wcf" %>
Run Code Online (Sandbox Code Playgroud)

我的WCF服务类Ajax定义如下:

namespace Generic.Frontend.Web
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(
        RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Ajax
    {
        public MapWebService MapWebService { get; set;}

        public Ajax() {
            // this constructor is being called
        }

        public Ajax(MapWebService mapWebService)
        {
            // this constructor should be called
            MapWebService = mapWebService;
        }

        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        [OperationContract(Name = "mapchange")]
        public MapChangeResult ProcessMapChange(string args)
        {
            // use the injected service here
            var result = MapWebService.ProcessMapChange(args);
            return result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我已经使用了Global.asax.cs如上面提到的wiki所示的接线:

var builder = new ContainerBuilder();
builder.RegisterModule(new AutofacModuleWebservice());
var container = builder.Build();
AutofacServiceHostFactory.Container = container;
Run Code Online (Sandbox Code Playgroud)

class AutofacModuleWebservice : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.Register<Ajax>();
        builder.Register<MapWebService>().ContainerScoped();
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的web.config中我有

<services>
    <service name="Generic.Frontend.Web.Ajax">
        <endpoint address="http://mysite.com/ajax.svc/" binding="webHttpBinding"
                  contract="Generic.Frontend.Web.Ajax" />
    </service>
</services>
Run Code Online (Sandbox Code Playgroud)

.

该服务已经正常工作,但我无法获得Autofac位(读取:创建/注入).有任何想法吗?

编辑: 删除默认构造函数不幸导致以下异常:

System.InvalidOperationException:
The service type provided could not be loaded as a service because it does not
have a default (parameter-less) constructor. To fix the problem, add a default
constructor to the type, or pass an instance of the type to the host.
Run Code Online (Sandbox Code Playgroud)

干杯,奥利弗

Igo*_*aka 0

尝试删除默认Ajax构造函数并将构造函数修改为此。如果它运行,mapWebService == null则表明存在解决问题。

    public Ajax(MapWebService mapWebService = null)
    {
        // this constructor should be called
        MapWebService = mapWebService;
    }
Run Code Online (Sandbox Code Playgroud)