没有 SVC 文件的 WCF 依赖注入

WCF dependency injection without SVC file

我有一个通过 net.pipe 公开的 WCF 服务。此服务的托管方式如下:

var hosturi = new Uri("net.pipe://localhost/somewhere");
var host = new ServiceHost(typeof(Service), hosturi);
var serviceBinding = new NetNamedPipeBinding
{
    MaxReceivedMessageSize = int.MaxValue, // and maybe something else
};

serviceBinding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas
{
    MaxArrayLength = int.MaxValue, // and maybe something else
};

host.AddServiceEndpoint(typeof(T), serviceBinding, string.Empty);
host.Description.Behaviors.Add(
    new ServiceThrottlingBehavior
    {
        MaxConcurrentCalls = 5000,
        MaxConcurrentInstances = 5000,
        MaxConcurrentSessions = 5000
    }
);
host.Open();

我想为我的服务实例指定 DI 工厂以获取注入的任何构造函数依赖项。

虽然有很多关于该主题的文章(例如此处:https://msdn.microsoft.com/en-us/library/hh323725(v=vs.100).aspx),但绝对所有文章都建议使用 .svc 文件指定工厂。

如何在代码中执行此操作?

您自己创建服务主机,因此您不需要 ServiceHostFactory(它是创建 ServceHost 的工厂)。因此,只需跳过文章中的步骤 4-6 并使用

向您的主机添加行为
host.Description.Behaviors.Add(new DependencyInjectionServiceBehavior());