如何使用Autofac与WCF无文件激活和自定义ServiceHostFactory?

时间:2015-05-11 17:53:59

标签: wcf dependency-injection autofac

我需要在CusotmServiceHostFactory中添加绑定/配置。但是,我想使用Autofac。我的CustomServiceHostFacotry如何实现AutofacServiceHostFactory?我使用无文件激活,所以我的配置部分如下所示:

<serviceActivations>                
  <add service="Project.Business.Services.AccountService" 
        relativeAddress="Account/AccountService.svc" 
        factory="Project.WebHost.CustomServiceHostFactory"/>
</serviceActivations>

这是我目前的定制工厂:

public class CustomServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<MyDbContext>().As<IDataContextAsync>();
        builder.RegisterType<UnitOfWork>().As<IUnitOfWorkAsync>();

        builder.RegisterGeneric(typeof (Repository<>)).As(typeof (IRepositoryAsync<>));

        builder.RegisterAssemblyTypes(typeof(AccountService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .As(t => t.GetInterfaces().FirstOrDefault(
                i => i.Name == "I" + t.Name));

        var container = builder.Build();
        var host = new CustomServiceHost(serviceType, baseAddresses);
        Type contractType = GetContractType(serviceType);
        host.AddDependencyInjectionBehavior(contractType, container);

        return host;
    }
    private static Type GetContractType(Type serviceType)
    {
        return serviceType.GetInterfaces()
            .FirstOrDefault(i => Attribute.IsDefined(i, typeof(ServiceContractAttribute), false));
    }
}

如您所见,我无处可设置AutfoacServiceHostFactory.Container属性。我已经尝试更改我的CustomServiceHostFactory来实现AutofacServiceHostFactory,如下所示:

public class CustomServiceHostFactory : AutofacServiceHostFactory

..但无论我做什么,当我发布到IIS并浏览服务时,我收到此错误:

  

必须先设置AutofacServiceHost.Container静态属性   服务可以实例化。

编辑1:我也试过了。

public class CustomServiceHostFactory : AutofacServiceHostFactory

然后分配给容器。我的原始代码在这里略有变化:

AutofacServiceHostFactory.Container = builder.Build();
var host = new CustomServiceHost(serviceType, baseAddresses);
Type contractType = GetContractType(serviceType);
host.AddDependencyInjectionBehavior(contractType, AutofacServiceHostFactory.Container);

这会产生同样的错误。事实上,当我在localhost上运行时,我甚至不再在调试时进入CreateServiceHost方法。浏览器只是呈现错误。这不是正确的切入点/组合根吗?

编辑2:原来这会起作用,但相当烦人。我必须使用字符串constructorString作为参数来覆盖此CreateServiceHost方法。如果我尝试覆盖其他方法签名(采用Type serviceType参数),我从未在该方法中遇到断点...不明白为什么。这似乎是一个黑客。为什么我没有进入CreateServiceHost(输入serviceType ... override?

public class CustomServiceHostFactory : AutofacServiceHostFactory
{
    public CustomServiceHostFactory()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<MyDbContext>().As<IDataContextAsync>();
        builder.RegisterType<UnitOfWork>().As<IUnitOfWorkAsync>();
        builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepositoryAsync<>));

        builder.RegisterAssemblyTypes(typeof(AccountService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .As(t => t.GetInterfaces().FirstOrDefault(
                i => i.Name == "I" + t.Name));

        Container = builder.Build();
    }

    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
        Type serviceType = GetType(constructorString);
        Type contractType = GetContractType(serviceType);
        var host = new CustomServiceHost(serviceType, baseAddresses);
        host.AddDependencyInjectionBehavior(contractType, Container);

        return host;
    }

    private static Type GetContractType(Type serviceType)
    {
        return serviceType.GetInterfaces()
            .FirstOrDefault(i => Attribute.IsDefined(i, typeof(ServiceContractAttribute), false));
    }

    private static Type GetType(string typeName)
    {
        var type = Type.GetType(typeName);
        if (type != null) return type;

        foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
        {
            type = a.GetType(typeName);
            if (type != null)
                return type;
        }

        return null;
    }
}

1 个答案:

答案 0 :(得分:7)

好的,终于搞定了。我希望这可以帮助别人。这是CustomServiceHostFactory:

public class CustomServiceHostFactory : ServiceHostFactory
{
    public CustomServiceHostFactory()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<MyDbContext>().As<IDataContextAsync>().InstancePerLifetimeScope();
        builder.RegisterType<UnitOfWork>().As<IUnitOfWorkAsync>().InstancePerLifetimeScope();
        builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepositoryAsync<>)).InstancePerLifetimeScope();

        builder.RegisterAssemblyTypes(typeof(AccountService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
            .As(t => t.GetInterfaces().FirstOrDefault(
                i => i.Name == "I" + t.Name)).InstancePerLifetimeScope();

        AutofacHostFactory.Container = builder.Build();
    }

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        Type contractType = GetContractType(serviceType);
        var host = new CustomServiceHost(serviceType, baseAddresses);
        host.AddDependencyInjectionBehavior(contractType, AutofacHostFactory.Container);

        return host;
    }

    private static Type GetContractType(Type serviceType)
    {
        return serviceType.GetInterfaces()
            .FirstOrDefault(i => Attribute.IsDefined(i, typeof(ServiceContractAttribute), false));
    }
}

这是CustomServiceHost代码(为简洁起见省略了实现):

public class CustomServiceHost : ServiceHost
{        
    public CustomServiceHost(Type serviceType, Uri[] baseAddresses)
        : base(serviceType, baseAddresses)
    {
    }

    protected override void ApplyConfiguration()
    {
        base.ApplyConfiguration();
        AddServiceDebugBehavior();
        AddWcfMessageLoggingBehavior();
        AddGlobalErrorHandlingBehavior();
        AddServiceCredentialBehavior();
        AddEndpoints();
        ConfigureThrottling();
    }

     //implement above methods here...
}

这是配置(重要部分):

<serviceHostingEnvironment>
  <!-- where virtual .svc files are defined -->
  <serviceActivations>                
    <add service="Project.Business.Services.AccountClassService" 
          relativeAddress="Account/AccountClassService.svc" 
          factory="Project.WebHost.CustomServiceHostFactory"/>

    <add service="Project.Business.Services.UserService"
          relativeAddress="User/UserService.svc"
          factory="Project.WebHost.CustomServiceHostFactory"/>
  </serviceActivations>
</serviceHostingEnvironment>

我的每个WCF服务都有这个行为属性,使它们在每次调用时都起作用(而不是默认的PerSession):

InstanceContextMode = InstanceContextMode.PerCall