2012-08-10 73 views
2

是否需要为不带.svc的自托管服务指定服务实施类型和主机工厂?当我尝试运行下面的控制台应用程序时,我收到一个没有默认构造函数的错误,所以看起来我的容器注册没有被使用。我错过了什么?使用WCF4自托管服务的自动配置(no .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); 
} 

回答

1

我想我已经想出了我在Alex Meyer-Gleaves的一篇博客文章中缺少的东西。我需要调用ComponentRegistry.TryGetRegistration

http://alexmg.com/post/2010/05/07/Self-Hosting-WCF-Services-with-the-Autofac-WCF-Integration.aspx

这里是我更新的代码:

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