WCF-如何在初始化服务主机TypeOfService-Class时传递服务类构造函数参数

问题描述

我有WCF服务类'MusicServiceManager',其构造函数采用IAppAmbientState的参数。我需要在初始化服务主机时将参数值传递给MusicServiceManager构造函数。我不想为IAppAmbientState实现单例。

服务合同

[ServiceContract]
public interface IAlbumService
{
    [OperationContract]
    string TestMessage();

    [OperationContract]
    IEnumerable<AlbumData> GetAlbums();

    [OperationContract(Name = "GetAlbumByID")]
    AlbumData GetAlbum(Guid ID);

    [OperationContract(Name = "GetAlbumByName")]
    AlbumData GetAlbum(string name);
}

AppAmbientState

public class AppAmbientState : IAppAmbientState
{
    public IContainer ServiceContainer { get; }

    public AppAmbientState(
        IContainer container  // autofac DIC container
        )
    {
        ServiceContainer = container;
    }
}

MusicServiceManager

public class MusicServicesManager : IAlbumService
{
    private readonly IAppAmbientState _appAmbientState;
   
    public MusicServicesManager(IAppAmbientState appAmbientState)
    {
        this._appAmbientState= appAmbientState;         
    }

    public AlbumData GetAlbum(Guid ID)
    {
        throw new NotImplementedException();
    }

服务主机配置类

public class ServiceHostConfiguration : IServiceHostConfiguration
{
    private readonly ServiceHost hostMusicServiceManager;

    public ServiceHostConfiguration()
    {
        var container = ContainerConfiguration.Configure();

        AppAmbientState AppAmbientStateInstance = new AppAmbientState(container);
        // need help here... MusicServiceManager(AppAmbientStateInstance)???? 
        // ideally I don't want to define my base address in class

        this.hostMusicServiceManager = new ServiceHost(typeof(MusicServicesManager));
    }

    public void InitializeService()
    {
        try
        {
            this.hostMusicServiceManager.Open();
            Console.WriteLine("App Web Services Started. Press [Enter] To Exit  ");
        }
        catch(Exception exp)
        {
            Console.WriteLine("App Web Services Could Not Start::  ",exp);
        }
        
    }

    public void CloseService()
    {
        this.hostMusicServiceManager.Close();
    }
}

Autofac DI容器

public static class ContainerConfiguration
{
    public static IContainer Configure()
    {
        var builder = new ContainerBuilder();
        
        //Application Configuration
        builder.RegisterType<Application>().As<IApplication>();
        builder.RegisterType<ServiceHostConfiguration>().As<IServiceHostConfiguration>();
        builder.RegisterType<AppAmbientState>().As<IAppAmbientState>();
        builder.RegisterType<MusicServicesManager>().As<IAlbumService>();

解决方法

这是我的演示:

这是项目目录:

enter image description here

Program.cs:

using Autofac;
using Autofac.Integration.Wcf;
using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace AutofacTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<Logger>().As<ILogger>();
            builder.RegisterType<Service>();

            using (IContainer container = builder.Build())
            {
                
                ServiceHost host = new ServiceHost(typeof(Service));
                host.AddDependencyInjectionBehavior<Service>(container);
                host.Open();
                Console.WriteLine("The host has been opened.");
                Console.ReadLine();
                host.Close();
              
            }
        }
    }
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        string Test();
    }

    public interface ILogger
    {
    }

    public class Service : IService
    {
        private readonly ILogger logger;

        
        public Service(ILogger logger)
        {
            this.logger = logger;
        }

        public string Test()
        {
            return "TEst1";
        }
    }

    public class Logger : ILogger
    {

    }
}

App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    <system.serviceModel>
        <services>
            <service name="AutofacTest.Service">
                <endpoint address="" binding="basicHttpBinding" contract="AutofacTest.IService" name="TestServiceEndPoint" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" name="TestServiceMexEndPoint" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost/TestService" />
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceDebug includeExceptionDetailInFaults="true" />
                    <serviceMetadata httpGetEnabled="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

如果问题仍然存在,请随时告诉我。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...