Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac register dll using Assembly.Load

I'm trying to register a dll named "BigEye.Business" and referenced that file to the mvc 3 project. But when i try to get instance of an object in that dll, autofac says it's not registered. Here is how i register and resolve the object:

private static IContainer SetDIContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UserAuthManager>().As<IUserAuth>().InstancePerHttpRequest();
            builder.RegisterType<SessionManager>().As<ISession>().InstancePerHttpRequest();


            //Here is the code to register that dll
            var services = Assembly.Load("BigEye.Business");
            builder.RegisterAssemblyTypes(services);
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            return container;
        }

        public static T GetInstance<T>()
        {
            IContainer container = SetDIContainer();

            using(var httpRequestScope = container.BeginLifetimeScope("httpRequest"))
            {
                return httpRequestScope.Resolve<T>();
            }

        }

And when i call GetInstance function i get "The requested service 'BigEye.Interfaces.Business.IUser' has not been registered". Should i register all the components in Business dll? Is there a way to do it? Because objects and services in Business will change in time.

Thanks

like image 810
mehmetserif Avatar asked May 10 '12 08:05

mehmetserif


1 Answers

I assume that your assembly contains one or more implementations of the IUser interface. Now, when you run:

 builder.RegisterAssemblyTypes(services);

without any additional parameters you are actually registering all types in that assembly keyed by class. You will probably see that this resolve works:

GetInstance<SomeSpecificUserImplementation>();

In order to key your services by interface, simply do the following:

  builder.RegisterAssemblyTypes(services).AsImplementedInterfaces();

Now all your services will be keyed by the interfaces they implement instead of the specific class, thus the following will work:

GetInstance<IUser>();
like image 53
Peter Lillevold Avatar answered Oct 15 '22 00:10

Peter Lillevold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!