The AutofacServiceHost.Container static property must be set before services can be instantiated

白昼怎懂夜的黑 提交于 2021-02-07 07:53:11

问题


Within my XXXX.WS WCF services project I'm trying to get DI/IOC using autofac going...been at it all day but I think I'm close (different errors are progress here)...this error I can't understand how to shake..."AutofacServieHost.Container static property must be set..."..but I think I am setting it!?! What am I doing wrong?

  protected void Application_Start(object sender, EventArgs e)
    {
        var builder = new ContainerBuilder();

        builder.Register(c => new DatabaseFactory()).As<IDatabaseFactory>().Named<DatabaseFactory>("DBFactory");
        builder.Register(c => new ListingSqlRepository(c.ResolveNamed<DatabaseFactory>("DBFactory"))).As<IListingSqlRepository>().Named<ListingSqlRepository>("LSR");
        builder.Register(c => new ListingRepository(c.ResolveNamed<ListingSqlRepository>("LSR"))).As<IListingRepository>().Named<ListingRepository>("LR");
        builder.Register(c => new Service1(c.ResolveNamed<IListingRepository>("LR"))).As<IService1>();

        using (var container = builder.Build())
        {
            Uri address = new Uri("http://localhost:57924/Service1");
            ServiceHost host = new ServiceHost(typeof(Service1), address);

            host.AddServiceEndpoint(typeof(IService1), new BasicHttpBinding(), string.Empty);

            host.AddDependencyInjectionBehavior<IService1>(container);

            //BREAKS HERE?
            host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = address });
            host.Open();

            Console.WriteLine("The host has been opened.");
            Console.ReadLine();

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

    }

Then the SERVICE: namespace LOTW2012.WS {

public class Service1 : IService1
{
    private IListingRepository _listingRepository { get; set; }

    public Service1(IListingRepository iLR) {
        this._listingRepository = iLR;
    }

    public Service1()
    {
    }


    public List<Listing> GetListingsByStateName(string stateName)
    {   
        //todo ..getall for now
        var listings = _listingRepository.GetAll().ToList();

        return listings;
    }

回答1:


You need to tell the Autofac WCF integration about the container you build by setting the property in question:

var builder = new ContainerBuilder();

// ...

AutofacHostFactory.Container = builder.Build();

// ...

This will allow Autofac to resolve service types.



来源:https://stackoverflow.com/questions/9846069/the-autofacservicehost-container-static-property-must-be-set-before-services-can

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!