3

.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);
}
4

1 に答える 1

2

AlexMeyer-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);
}
于 2012-08-10T20:03:22.383 に答える