简体   繁体   中英

How to use Autofac from class library in asp.net Mvc project?

I registered my classes in a class library project as follows:

public static ContainerBuilder Init()
{
    var builder = new ContainerBuilder();
    var assemblies = ConfigurationManager.AppSettings["IocAssembly"].Split(',');
    for (int i = 0; i < assemblies.Length; i++)
    {
        var assemblyName = assemblies[i];
        foreach (var type in Assembly.Load(assemblyName).GetTypes())
        {
            type.GetInterfaces().Where(x => x.Namespace == string.Concat(assemblyName, ".Contract")).ToList().ForEach
                (s => builder.RegisterType(type).As(s).InstancePerLifetimeScope());
        }
    }

    return builder;
}

And then added reference to that dll fin my asp.net project and tried to build container as you can see:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    var container=AutofacInitializer.Init();
    container.Build();
}

But nothing happened and i got error

No parameterless constructor defined

for my controller... Where i'm wrong?

You didn't set the DependencyResolver .

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Documentation here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM