关于WCF与Autofac的整合

1 、客户端:

// 创建一个容器
var builder = new ContainerBuilder();

// 注册一个服务通道工厂
builder.Register(c => new ChannelFactory<ITrackListing>(
    new BasicHttpBinding(),
    new EndpointAddress("http://localhost/TrackListingService")))
  .SingleInstance();

// 通过工厂创建通道
builder.Register(c => c.Resolve<ChannelFactory<ITrackListing>>().CreateChannel())
  .UseWcfSafeRelease();
// 注册AlbumPrinter
builder.RegisterType<AlbumPrinter>();

var container = builder.Build();

不过,创建通道并不是立即执行,而是真正请求服务的时候,才创建的。

服务调用:

class AlbumPrinter
{
  readonly ITrackListing _trackListing;

  public AlbumPrinter(ITrackListing trackListing)
  {
    _trackListing = trackListing;
  }

  public void PrintTracks(string artist, string album)
  {
    foreach (var track in _trackListing.GetTracks(artist, album))
      Console.WriteLine("{0} - {1}", track.Position, track.Title);
  }
}
嵌套的生命周期下调用服务的方式:
using(var lifetime = container.BeginLifetimeScope())
{
  var albumPrinter = lifetime.Resolve<AlbumPrinter>();
  albumPrinter.PrintTracks("The Shins", "Wincing the Night Away");
}

 2、使用IIS承载服务

服务端注册服务
var builder = new ContainerBuilder();
builder.RegisterType<TestService.Service1>();
AutofacHostFactory.Container = builder.Build();

svc文件:(服务描述注意要用全名: Service="Namespace.ServiceType, AssemblyName")

<%@ ServiceHost
    Service="TestService.Service1, TestService"
    Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" %>

如果要注册命名的服务:

var builder = new ContainerBuilder();
builder.RegisterType<TestService.Service1>().Named<object>("my-service");
AutofacHostFactory.Container = builder.Build();

相应的.svc文件如下:

<%@ ServiceHost
    Service="my-service"
    Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" %>

服务端注入:

        protected void Application_Start(object sender, EventArgs e)
        {
            // Create the tenant ID strategy.
            var tenantIdStrategy = new OperationContextTenantIdentificationStrategy();
            // Register application-level dependencies and service implementations.
            var builder = new ContainerBuilder();
            builder.RegisterType<MyService>().As<ITestService>();
            builder.RegisterType<BaseDependency>().As<IDependency>();
            builder.RegisterType<CustomerService>().As<ICustomerService>();

            builder.RegisterInstance(new OrderDto() { ID = 999, ProductName = "the message from test.com!" });
            builder.RegisterType<OrderService>().As<IOrderService>();

            // Create the multitenant container.
            var mtc = new MultitenantContainer(tenantIdStrategy, builder.Build());
            // Notice we configure tenant IDs as strings below because the tenant
            // identification strategy retrieves string values from the message
            // headers.
            // Configure overrides for tenant 1 - dependencies, service implementations, etc.
            mtc.ConfigureTenant("1",
            b =>
            {
                b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency();
                b.RegisterType<Tenant1Implementation>().As<ITestService>();
                b.RegisterType<CustomerService>().As<ICustomerService>();
            });

            // Add a behavior to service hosts that get created so incoming messages
            // get inspected and the tenant ID can be parsed from message headers.
            AutofacHostFactory.HostConfigurationAction =
            host =>
                host.Opening += (s, args) =>
                host.Description.Behaviors.Add(new TenantPropagationBehavior<string>(tenantIdStrategy));

            // Set the service implementation strategy to multitenant.
            AutofacHostFactory.ServiceImplementationDataProvider =
                new MultitenantServiceImplementationDataProvider();

            // Finally, set the host factory application container on the multitenant
            // WCF host to a multitenant container.
            AutofacHostFactory.Container = mtc;
        }

 
原文地址:https://www.cnblogs.com/shi5588/p/WCF.html