Search code examples
wcfdependency-injectionautofac.net-4.8

Register WCF service in Autofac Container within Console App


I have .NET 4.8 Console application with WCF in a separate project. I have register all my class in Autofac container, followed by MyServiceManager which is the implementation of ServiceContract but getting an error, not sure what I am missing from the puzzle

Error

System.ArgumentException: 'The service contract type 'App.WCF.Service.ServicesManager.MyServiceManager' has not been registered in the container.

Parameter name: contractType'

Console App

 public static void Main(string[] args)
    {
        Console.WriteLine("Initialise Application....");

        var buildContainer = CompositionRoot();

        ServiceHost appHostServices = new ServiceHost(typeof(MyServiceManager));
        appHostServices.AddDependencyInjectionBehavior<MyServiceManager>(buildContainer); //Getting Error Here
        appHostServices.Open();
        Console.WriteLine("opening webservices....");
        
        buildContainer.Resolve<MyApplication>().Run();

        Console.ReadLine();
        appHostServices.Close();
    }

    private static IContainer CompositionRoot()
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<MyApplication>();
        builder.RegisterType<CallMyMessage>().As<ICallMyMessage>();
        builder.RegisterType<Message>().As<IMessage>();

        return builder.Build();
    }

}

Solution

  • Based on the shown code, MyServiceManager is not registered in the container.

    private static IContainer CompositionRoot()
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<MyApplication>();
        builder.RegisterType<CallMyMessage>().As<ICallMyMessage>();
        builder.RegisterType<Message>().As<IMessage>();
    
        builder.RegisterType<MyServiceManager>(); //<-- Was missing
    
        return builder.Build();
    }
    

    The container needed to know how to resolve the contract type since it is being used to manage dependency injection in the service host.