determig
determig

Reputation: 51

Autofac with class library

I have a C# solution containing

-MVC project
-WCF Project
-Service library
-Model (Entity Framework)

The MVC Project is getting all the data from the web service. And the WCF Service is getting the data from the service library.

I'm now trying to implement DI with Autofac.

What I have done so far is to create three classes in the service library.

public class ServiceModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(Assembly.Load("Foot.Service"))
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
    }
}

public class EFModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType(typeof(FootContext)).As(typeof(IContext)).InstancePerLifetimeScope();
    }
}

public class Init
{
    public Init()
    {
        //Autofac Configuration
        var builder = new Autofac.ContainerBuilder();
        builder.RegisterModule(new ServiceModule());
        builder.RegisterModule(new EFModule());
        var container = builder.Build();

    }
}

Is this the right way to go? And then call the Init() in the WCF library?

And should I do the same thing for the WCF service?

Upvotes: 3

Views: 2921

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27871

I can see two applications in your solution. The first application is the MVC project. And the second application is the WCF service. The other projects are class libraries and not applications.

What you need to do is make sure that only applications have Composition Roots, i.e., only applications should compose objects at their entry point.

Quoting from the referenced article:

Only applications should have Composition Roots. Libraries and frameworks shouldn't.

So, the only places where you should reference a DI container is the two mentioned applications. So, in your case, this means that you should register the types from the Service and Model libraries in the WCF service project. The Service and Model libraries should not have any reference to the DI container.

Upvotes: 2

Related Questions