WCF:没有为此对象依赖项注入简单注入器定义无参数构造函数



我已经将简单的注入器配置为我的DI容器。我遵循了这个。我猜我的问题与将容器注册到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();
}

定制服务工厂

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>
您应该在

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>

最新更新