Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac IoC GetInstance method

I'm trying to use autofac in my project. So in Mef i could get the instance of an interface with this code:

private static CompositionContainer _container;

        public static void Initialize()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory.Contains(@"\bin") ?
                AppDomain.CurrentDomain.BaseDirectory :
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");

            //DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"), "*.Data*.dll");
            DirectoryCatalog catalog = new DirectoryCatalog(path, "*.dll");
            _container = new CompositionContainer(catalog);
            _container.ComposeParts();
        }

        private static void CheckContainer()
        {
            if (_container == null)
            {
                Initialize();
            }
        }

        public static T GetInstance<T>()
        {
            CheckContainer();

            return _container.GetExportedValue<T>(); 
        }

But autofac seems confusing to me... How can i add this feature to my app using autofac?

Thanks


I changed that code to this:

private static ContainerBuilder _container;
        private static IContainer container;

        public static void Initialize()
        {
            _container = new ContainerBuilder();
            var logging = Assembly.Load("StarlightFramework.Logging");
            _container.RegisterAssemblyTypes(logging);
            container = _container.Build();

        }

        public static T GetInstance<T>()
        {
            if(container == null)
                Initialize();
            return container.Resolve<T>();
        }

But i get this error this time: "Could not load file or assembly 'Autofac, Version=2.6.1.841, Culture=neutral, PublicKeyToken=17863af14b0044da' or one of its dependencies. "

What might be the problem?

like image 812
mehmetserif Avatar asked May 04 '12 08:05

mehmetserif


1 Answers

First you have to build your container and register your services.

var builder = new ContainerBuilder();
builder.RegisterType<MyService>().As<IMyService>(); 
var container = builder.Build();

Then you can get an instance of a registered service using the Resolve extension method.

var service = container.Resolve<IMyService>();
like image 151
Marek Dzikiewicz Avatar answered Oct 27 '22 01:10

Marek Dzikiewicz