Autofac IoC GetInstance method
Solution 1
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>();
Solution 2
Make sure that the Autofac.dll assembly is present in your application's bin folder and that the assembly has the same version as the one used used by StarlightFramework.Logging.
mehmetserif
Updated on June 10, 2020Comments
-
mehmetserif almost 4 years
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?
-
mehmetserif almost 12 yearsWell i tried this method but i got an error: "ILogger has not been registered. either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.". But i register "ILogger". What is missing?