WCF:没有为此对象依赖注入Simple Injector定义的无参数构造函数

时间:2016-04-21 09:22:09

标签: c# wcf simple-injector

我已将简单的进样器配置为我的DI容器。我跟着this。 我猜我的问题与将容器注册到SimpleInjectorServiceHostFactory有关。 我正在使用类库来托管Web应用程序上的wcf服务。我没有.svc文件,但我配置了相对地址。我在哪里进行集装箱登记?

public static class ContainerBootstrap
{
    public static Container Container { get; set; }

    static ContainerBootstrap()
    {
        var container = new Container();

        container.Options.DefaultScopedLifestyle = new WcfOperationLifestyle();

        container.RegisterSingleton<ITypeAdapterFactory, AutomapperTypeAdapterFactory>();

        container.Register<IDepartmentService, DepartmentService>();

        var typeAdapterFactory = container.GetInstance<ITypeAdapterFactory>();
        TypeAdapterFactory.SetCurrent(typeAdapterFactory);

        Container.Verify();

        Container = container;
    }
}

AutomapperTypeAdapterFactory:

public class AutomapperTypeAdapterFactory : ITypeAdapterFactory
{
    public AutomapperTypeAdapterFactory()
    {
        var profiles = AppDomain.CurrentDomain
                                .GetAssemblies()
                                .SelectMany(a => a.GetTypes())
                                .Where(t => t.BaseType == typeof(Profile));

        var config = new MapperConfiguration(cfg =>
        {
            foreach (var profile in profiles)
            {
                if (profile.FullName != "AutoMapper.SelfProfiler`2")
                    cfg.AddProfile(Activator.CreateInstance(profile) as Profile);
            }
        });

        ContainerBootstrap.Container.Register<MapperConfiguration>(() => config);
        ContainerBootstrap.Container.Register<IMapper>(() => 
            ContainerBootstrap.Container.GetInstance<MapperConfiguration>()
                .CreateMapper());
    }

    public ITypeAdapter Create() => new AutomapperTypeAdapter();
}

自定义ServiceFactory

public class WcfServiceFactory : SimpleInjectorServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        return new SimpleInjectorServiceHost(ContainerBootstrap.Container, serviceType, 
            baseAddresses);
    }
}

在WebHost web.config

<serviceActivations>
  <add factory="Department.InstanceProviders.WcfServiceFactory" 
       service="Department.DepartmentService" relativeAddress="DepartmentService.svc" />
</serviceActivations>

1 个答案:

答案 0 :(得分:4)

您应该在web.config文件中的serviceActivation元素下添加工厂条目。这可确保SimpleInjectorServiceHostFactory用于激活服务。

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
    multipleSiteBindingsEnabled="true">
    <serviceActivations>
        <add factory="SimpleInjector.Integration.Wcf.SimpleInjectorServiceHostFactory,
SimpleInjector.Integration.Wcf"
            relativeAddress="~/Service1.svc"
            service="TestService.Service1" />
    </serviceActivations>
</serviceHostingEnvironment>