gpt4 book ai didi

wcf - 带有 WCF4 自托管服务的 Autofac(无 .svc)

转载 作者:行者123 更新时间:2023-12-04 13:42:24 25 4
gpt4 key购买 nike

没有.svc的自托管服务是否需要指定服务实现类型和宿主工厂?当我尝试运行下面的控制台应用程序时,我收到一个没有默认构造函数的错误,所以我的容器注册似乎没有被使用。我错过了什么?

var builder = new ContainerBuilder();
builder.Register(c => new GenericRepository()).As<IRepository>();
builder.Register(c => new BusinesLogic(c.Resolve<IRepository>())).As<IBusinesLogic>();
builder.Register(c => new MyService(c.Resolve<IBusinesLogic>())).As<IMyService>();

using (IContainer container = builder.Build())
{
var address = new Uri("net.tcp://localhost:8523/MyService");
var host = new ServiceHost(typeof(MyService), address);

host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), string.Empty);
host.AddDependencyInjectionBehavior<IMyService>(container);
host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = false });
host.Open();

Console.WriteLine("Navigate to the following URI to see the service.");
Console.WriteLine(address);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();

host.Close();
Environment.Exit(0);
}

最佳答案

我想我已经弄清楚我在 Alex Meyer-Gleaves 的博客文章中遗漏了什么。我需要调用 ComponentRegistry.TryGetRegistration

https://alexmg.com/posts/self-hosting-wcf-services-with-the-autofac-wcf-integration

这是我更新后的代码:

var builder = new ContainerBuilder();
builder.Register(c => new GenericRepository()).As<IRepository>();
builder.Register(c => new BusinessLogic(c.Resolve<IRepository>())).As<IBusinessLogic>();
builder.Register(c => new MyService(c.Resolve<IBusinessLogic>())).As<IMyService>();

using (IContainer container = builder.Build())
{
var address = new Uri("net.tcp://localhost:8523/MyService");
var host = new ServiceHost(typeof(MyService), address);

host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), string.Empty);

IComponentRegistration registration;
if (!container.ComponentRegistry.TryGetRegistration(new TypedService(typeof(IMyService)), out registration))
{
Console.WriteLine("The service contract has not been registered in the container.");
Console.ReadLine();
Environment.Exit(-1);
}

host.Description.Behaviors.Add(new AutofacDependencyInjectionServiceBehavior(container, typeof(MyService), registration));
host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = false });
host.Open();
Console.WriteLine("Navigate to the following URI to see the service.");
Console.WriteLine(address);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();

host.Close();
Environment.Exit(0);
}

关于wcf - 带有 WCF4 自托管服务的 Autofac(无 .svc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com