FAQ Database Discussion Community


add Autofac extension to throw exception if not appropriately injected into approved type

c#,dependency-injection,autofac
I'm attempting to create an Autofac extension method that will throw an exception when a registered type is created for an object that is not an approved object type. public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> OnlyForInheritorsOf<TLimit, TReflectionActivatorData, TStyle>( this IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> registration, Type baseType) where TReflectionActivatorData : ReflectionActivatorData { return...

How to register a type with autofac after container creation

c#,inversion-of-control,registration,autofac
I have an infrastructure singleton that I would like resolved out of autofac At container creation I register AppPaths as a singleton However, for a variety of reasons (testing, a few infrastructure things) I would like to be able to swap that instance out with a new one during runtime....

Uses of PreserveExistingDefaults?

.net,dependency-injection,autofac
Why and when should we use PreserveExistingDefaults during autofac registration? I have read it's uses form Autoface docs: http://docs.autofac.org/en/latest/register/registration.html But my question is, when is the case we will register multiple implementation with single interface. Can anybody give some example from real time....

Using Autofac with Web Api 2 and Owin

c#,dependency-injection,autofac,asp.net-web-api2,owin
Im new to DI libraries and trying to use Autofac in a WebApi 2 project with Owin. This is my Owin Startup class, [assembly: OwinStartup(typeof(FMIS.SIGMA.WebApi.Startup))] namespace FMIS.SIGMA.WebApi { public class Startup { public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); var config = new HttpConfiguration(); WebApiConfig.Register(config); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); var...

registering 2 components which inherits same interface

c#,autofac,ioc-container
I am new in autofac and I am trying to understand the concept. So basically going through the sample on their website. I was playing around with some code and I didn't understand the following. If I register two similar components like todaywriter and yesterdaywriter as below and resolve my...

How do I use Autofac instead singleton in c#?

c#,asp.net-mvc,c#-4.0,singleton,autofac
I have used singleton pattern a using static property, constructor public class MyClass { private readonly MemoryCacheManager _cacheManager; private static readonly Lazy<MyClass> _Lazy = new Lazy<MyClass>(() => new MyClass()); public static MyClass Language { get { return _Lazy.Value; } } private MyClass() { _cacheManager = new MemoryCacheManager(); LoadCacheData(); } //...

Is there a way to resolve or configure the container to resolve a default object if one isn't found?

c#,dependency-injection,autofac
I would like to be able to inject a DefaultService object that implements IService<in T>. For example if I've got a constructor: public FunClient(IDefaultService<FunModel> service) { ... } But I don't have a FunService : IService<FunModel> developed, I would like to be able to tell Autofac to not throw an...

No IUserTokenProvider is registered when using dependency injection

c#,asp.net-mvc,owin,autofac
I got an error when my GeneratePasswordResetTokenAsync() method is call. I configured autofac with owin identity. The error is : No IUserTokenProvider is registered when using dependency injection In my sample.web project there is a AutofacConfig.cs file where I register signinmanager and usermanager which I created in sample.repository project. AutofacConfig.cs...

Fetching records taking some time using repository and dependency injection

asp.net-mvc,dependency-injection,repository-pattern,autofac,unit-of-work
I am creating 1 demo application to study repository and dependency injection. I am having just 10 to 15 records in my database tables and when reading it is taking some amount of times and i dont know why.is it because of repository or dependency injection?? so Please guide me...

Is there a way to pass a child container into the NserviceBus pipeline?

c#,wcf,autofac,nservicebus
Problem: A request sent to a WCF service, which calls IBus.SendLocal creates two instances of an object configured as InstancePerLifetimeScope() Background: I'm using Autofac.Integration.WCF (which makes everything resolve 'per request', by providing a new child scope to each WCF request) IBus.SendLocal invokes a message mutator, which gets injected with the...

AutoFac constructor multiple Interface

c#,.net,model-view-controller,castle-windsor,autofac
I am using Autofac in my project. I want to use a simple interface to resolve them. Not generic repository. I was using Castle in my old projects. It has a class which have static methods. I used it in my constructor method like this; IService.ProductService.GetMyProducts(); In Autofac i couldnt...

Subscribe mt queue to autofac module

autofac,masstransit
I'm trying to setup a single service that is broken into several logical services. Because they are logical services, they each get there own queue. Each logical service is a module in autofac. The setup looks vaguely like: sbc.ReceiveEndpoint(host, "service1", ep => { ep.LoadFrom(c.Resolve<ILifetimeScope>()) }); sbc.ReceiveEndpoint(host, "service2", ep => {...

Seeking example of how to tell Autofac which service to inject by name

c#,attributes,autofac,inject
I need an attribute like [WithNamed("x")] that will tell Autofac how to inject each 'service' with the correct parameter as shown. The constructor to be injected with two versions of FlagXCtlr: public CoupDo( [WithName("FLAG6")]ItemUserFlagCtrl Flag6Ctlr, [WithName("FLAG5")]ItemUserFlagCtrl Flag5Ctlr) { ... } Registering is done as so: builder.RegisterType<ItemUserFlagCtrl>() .Named<IItemUserFlagCtrl>("FLAG6") .WithParameter("userFlagParm", "FLAG6") .SingleInstance();...

Autofac Repository Pattern and Unit Of Work

entity-framework,design-patterns,repository,autofac,unit-of-work
I have searched a little bit and I am confused. First Approach uses a repository and a service for each entity with Autofac. Unit of work class does not have repositories. Therefore, you should create each repository instead of just creating one unit of work class in caller constructor. OrderService(IUnitOfWork...

Resolve parameters according to the parent tree that triggered the resolve?

c#,dependency-injection,autofac,dryioc
I have code similar to this: class A: IA { ... } class B: IB { public B(IA a, ...) { ... } ... } class C1 { public C1(IA a, IB b, ...) { ... } } class C2 { public C2(IA a, IB b, ...) { ... }...

Autofac instance management?

wcf,dependency-injection,autofac
Lets say I manually instantiate my objects like this: var context = new MyDbContext(); _uow = new UnitOfWork(context); _repository = new Repository<Account>(context, _uow); Instead, I want to inject them and register them like so: private readonly IUnitOfWorkAsync _uow; private readonly IRepositoryAsync<Account> _repository; public AccountService(IUnitOfWorkAsync uow, IRepositoryAsync<Account> repository) { _uow =...

Issues with hangfire job activation and Autofac

c#,autofac,hangfire
I'm triying to implement hangfire in my projects. I have a issue when I add a RecurringJob to hangfire, when it's fired i get this error: Autofac.Core.Registration.ComponentNotRegisteredException The requested service 'XXXX.Services.ScheduleTasks.RepairNotificationSevice' has not been registered. To avoid this exception, either register a component to provide the service, check for service...

properly call EF SaveChanges after each request with Autofac managing scope

entity-framework,owin,autofac,middleware
I would like to put in a bit of infrastructure on my project to SaveChanges on my db context at the end of every request. So I create a simple piece of Owin middleware app.Use(async (ctx, req) => { await req(); var db = DependencyResolver.Current.GetService<MyDbContext>(); await db.SaveChangesAsync(); }); This does...

Autofac - How to get class name while creating instance

c#,dependency-injection,inversion-of-control,autofac,ioc-container
I have question about Autofac : How can I get name of class which request instance from container? Is it possible to get name of the class "Autofac_Test" passed into constructor by autofac when object is created? My code: using System; using System.Diagnostics; using System.Reflection; using Autofac; using Xunit; public...

Use Autofac to inject a list of specified keyed/named items into component

c#,autofac
I have an interface IService of which I have multiple implementations. I have a class ConsumerClass which takes an IEnumerable<IService> as a parameter. I realise that if I just leave it, Autofac will automatically create the enumerable and fill it with all registered service implementations, but I'd like to specify...

Autofac TypeLoadException when upgrading MVC 4 -> 5

asp.net-mvc,asp.net-mvc-5,autofac
Trying to upgrade a project from MVC3to MVC5, the 3->4 part went well and I could run the project. However, after updating probably everything for mvc5, I'm getting an exception Inheritance security rules violated by type: 'Autofac.Integration.Web.Mvc.AutofacControllerFactory'. Derived types must either match the security accessibility of the base type or...

how Parameterized Instantiation work with SingleInstance lifescope

c#,autofac
In Parameterized Instantiation (Func<X, Y, B>) documentation, last sentence said However, if you register an object as SingleInstance() and call the Func to resolve the object more than once, you will get the same object instance every time regardless of the different parameters you pass in. Just passing different parameters...

How to make an optional dependency in AutoFac?

.net,autofac,default-value
I've got an interface, implementation, and target: public interface IPerson { public string Name { get; } } public class Person: IPerson { public string Name { get { return "John"; } } } public class Target { public Target(IPerson person) {} } I'm using Autofac to tie things together:...

What is the disadvantage of manually registering Log4Net Logger instance to ILog in Autofac?

c#,asp.net,log4net,autofac
Autofac has log4net Integration Module called LoggingModule. However, I register Logger to ILog manually without using LoggingModule, and it seems working fine. ILog log = LogManager.GetLogger("Logger"); builder.RegisterInstance(log).As<ILog>().SingleInstance(); My question is - what is the disadvantage/side effect of using above approach instead of using LoggingModule. web.config <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections>...

How to use Autofac with WCF fileless activation and a custom ServiceHostFactory?

wcf,dependency-injection,autofac
I need to add binding/configuration in my CusotmServiceHostFactory. However, I would like to use Autofac. How can my CustomServiceHostFacotry implement AutofacServiceHostFactory? I'm using fileless activation so my config section looks like this: <serviceActivations> <add service="Project.Business.Services.AccountService" relativeAddress="Account/AccountService.svc" factory="Project.WebHost.CustomServiceHostFactory"/> </serviceActivations> Here is my current custom factory: public class CustomServiceHostFactory :...

Autofac: How do you register a generic with multiple type arguments? Registering IGenRepo with EFGenRepo

c#,entity-framework-6,autofac,asp.net-mvc-5.2,.net-4.5.2
I am trying to build a generic repo and use autofac for testing. I have the following interface: public interface IGenRepo<T, TKey> where T : class { IQueryable<T> Items { get; } T find(TKey pk); RepoResult delete(TKey pk); RepoResult create(T item); RepoResult update(T item); RepoResult save(); } And here is...

Ways of loading external dll and injecting conditionally multiple implementations using autofac

c#-4.0,dll,reflection,autofac
i have an interface called say IMyHook which has some implementation in an external project(dll). i use this interface in my businesslogic classes and on my application startup i inject external implementation of this interface using Autofac. my interface public interface IMyHook { public void MyHookMethod(); } my business logic...

Resolving class that has extension methods with AutoFac

entity-framework,autofac,graphdiff
I am using a third party library GraphDiff which adds Extension methods to DBContext class. My Context class is inherited from Interface like following MyContext: DbContext,IMyContext IoC contained register MyContext as IMyContext. Interface doesn't have extension method's signature and third. Now i am not getting how MyContext will have that...

Can I access the full power of Autofac in UnitTests, using the Moq integration

c#,unit-testing,mocking,moq,autofac
My project (which happens built on top of Orchard, though I don't think that's relevant) uses Autofac. I am writing unit tests in which I want to stub out any dependencies using Moq, and I'm using the Autofac/Moq integration to achieve this. This is fine for any simple dependencies that...

Register Keyed implementation with Autofac receiving an ArgumentException (Type X not assignable to service Y)

c#,generics,autofac
I'm registering some concrete types using the Autofac Keyed options. This all appeared to be working fine until I added a generic parameter to the types and interface. My registration looks like this: builder.RegisterType<Customer.DataAccess.Database.StoreElasticConnectionManagerByCompany>(); builder.RegisterType<Customer.DataAccess.Database.StoreElasticConnectionManagerByStore>(); builder.RegisterType<Customer.DataAccess.Database.StoreElasticConnectionManager>();...

autofac: registering the same class more than once with different dependencies

c#,autofac
Given the following heirarchy: I need to resolve one instance of ProducerRepository per registered IParser dependency when an IEnumerable<ISourceRepository<IDatum>> is resolved. public class ProducerRepository : ISourceRepository<Data> { public ProducerRepository(IRepository repository) {} } public interface ISourceRepository<out T> where T : class, IDatum {} public class Repository : IRepository { public Repository(IParser...

How to update registered instances in Autofac container in runtime

c#,asp.net-mvc,dependency-injection,inversion-of-control,autofac
I want to replace existing registered instances in Autofac with new ones in ASP.NET MVC application in runtime. Registrations are keyed as I work with collections of instances of different subtype, though it seems to be irrelevant to my issue. Initial registration on application startup foreach (var instance in instances)...

Autofac cannot resolve class [duplicate]

c#,asp.net-mvc,entity-framework,autofac
This question already has an answer here: How to resolve Autofac InstancePerHttpRequest 2 answers I'm building an application with ASP.Net MVC for the back-end. Autofac is being used for dependency injection. Several components/classes are registered as InstancePerRequest. The Entity Framework context and unit of work (just a wrapper that...

Autofac - DelegatingHandler (HttpMessageHandler) Registration

c#,web-api,asp.net-web-api2,autofac,ioc-container
I have a custom DelegatingHandler in a class library that I need to register with Autofac. The webapi host resolves it's dependencies on runtime, so the host has no references to this library. public class LocalizationHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken ) {}...

using Autofac with XML configuration

c#,xml,dependency-injection,autofac
I am trying to decouple an implementation where the interface is know and the implementation would be defined in App.Config. But it doe not seem to be able to resolve the interface. This is what I am doing : <configuration> <autofac defaultAssembly="My.Service"> <components> <component type="My.Services.Service, My.Service" service="My.Abstractions.IService, My.Service" instance-scope="per-lifetime-scope" instance-ownership="lifetime-scope"...

Autofac register nested type?

c#,dependency-injection,autofac
Lets say I have these four types (with constructors). public class MyDbContext : IDataContextAsync { public class MyDataContext() { } } public class UnitOfWork : IUnitOfWorkAsync { public UnitOfWork(IDataContextAsync dataContext) { _dataContext = dataContext; } } public class Repository<TEntity> : IRepositoryAsync<TEntity> { public Repository(IDataContextAsync context, IUnitOfWorkAsync unitOfWork) { _context =...

How to resolve list of dependencies in Autofac?

c#,dependency-injection,autofac
I want register type, than resolve type, and then register instance using resolved values. Something like this: //Register type: builder.RegisterType<ValidateImportMandatoryColumns>().Named<IValidateImport>("MandatoryColumn").As<IValidateImport>(); builder.RegisterType<ValidateImportNonMandatoryColumns>().Named<IValidateImport>("NonMandatoryColumns").As<IValidateImport>(); //Resolve var t1 = Container.ResolveNamed<IValidateImport>("MandatoryColumn"); var t2 =...

Can Autofac IStartable be used with NServiceBus when the startable component needs IBus?

asp.net-mvc,bootstrap,nservicebus,autofac
The scenario here is that there is a component that needs to run some initialisation code on start-up. This is achieved by having the code implement Autofac.IStartable.Start and registering the code as IStartable. This code is then used in several contexts: A couple of ASP.NET websites, an NServiceBus.Host.exe hosted NSB...

Asp.net web api with autofac and Hangfire

autofac,owin,hangfire
I recently upgraded to a new version of Hangfire and I am struggeling trying to setup my webapi with autofac and Hangfire. I'm using Autofac Hangfire integration version 1.1 and Hangfire 1.4.2. I'm using Owin to host. I keep getting following error: The requested service 'IFoo' has not been registered....

Autofac constructor chaining

c#,inversion-of-control,decorator,autofac
How would I implement the equivalent using Autofac to output 123. I've had a look at the following but I don't think it quite fits in with what I'm trying to achieve. http://docs.autofac.org/en/latest/advanced/adapters-decorators.html Maybe someone can enlighten me - is this decorator? using System; namespace Prototypes.Decorator { public class Program...

DependencyResolutionException Circular component dependency detected: How to use Autofac to inject decorator?

c#,dependency-injection,mono,decorator,autofac
I have an interface called ILastActivityUpdator as follows: public interface ILastActivityUpdator { void UpdateLastActivity(int userId); } Besides that I have two classes that implement this interface, being LastActivityUpdator and a decorator AnonymousUserLastActivityUpdator. The latter one takes an ICookieProvider as extra argument and uses this in the method implementation. I.e., public...

Read Autofac xml configuration from DB and change it runtime

xml,configuration,inversion-of-control,autofac,code-injection
i'm having trouble searching for documentation and example reguarding autofac so i ask this here: i need to change at runtime the xml configuration that autofac accept to inject the implementations. I've thinked a scenario like this: a db field that is maintained and that decide how to configure Autofac....

Commands can not be solved with Autofac when stored in a List

c#,list,autofac,command-pattern,dependency-resolver
If have the code below, implementing the command pattern. I want to store several commands in a list and afterwards pick them from the list, resolve a commandhandler and finally execute the command. When implementing this I ran into the problem, that resolving a single command worked from Autofac but...

Generic registration with Autofac?

wcf,dependency-injection,autofac
I can manually register my repositories like so: builder.RegisterType<Repository<Account>>().As<IRepositoryAsync<Account>>(); builder.RegisterType<Repository<User>>().As<IRepositoryAsync<User>>(); builder.RegisterType<Repository<Order>>().As<IRepositoryAsync<Order>>(); But can't seem to register them automatically. I've tried a few things with no luck, namely this: builder.RegisterAssemblyTypes(typeof(Account).Assembly) .Where(t =>...

Autofac Resolve using delegate factory by type

c#,inversion-of-control,autofac
I am using Autofac for IoC in my project. Due to some legacy software libraries I must pass some services to the controller that can't be resolved, and must be passed as parameter. I've made a generic control using delegate factories like this: public MyClass<TController, TInterface> { private delegate TController...

Autofac resolves multiple instances of the same type

c#,autofac,mediatr
I have a slightly modified version of Mediatr handing command processing in my application. I have implemented a MediatorPipeline that allows me to have pre and post processors. public class AsyncMediatorPipeline<TRequest, TResponse> : IAsyncRequestHandler<TRequest, TResponse> where TRequest : IAsyncRequest<TResponse> { private readonly IAsyncRequestHandler<TRequest, TResponse> inner; private readonly IAsyncPreRequestHandler<TRequest>[] preRequestHandlers; private...

Use one instance in multiple components with Autofac

c#,asp.net-mvc,entity-framework,inversion-of-control,autofac
So I have an IApplicationDbContext class and an ApplicationDbContext class that implements it. In the code written by me I use IApplicationDbContext, but higher up on the chain MVC uses ApplicationDbContext and I can't really change that, so at the moment I have registered components like this: builder.RegisterType<ApplicationDbContext>() .AsSelf() .InstancePerRequest();...

Autofac Generic Multiple Interface

c#,dependency-injection,domain-driven-design,inversion-of-control,autofac
I am trying to resolve one generic interface something like below but I am getting exception when trying to run the application . public interface IHandler<in T> where T : IDomainEvent { void Handle(T args); } public class ApplicationUserCreatedEventHandler : IHandler<ApplicationUserCreatedEvent> { public void Handle(ApplicationUserCreatedEvent args) { if (args ==...

how to add custom configSections to app.config file through code

c#,winforms,autofac
How can I add sections to an app.config file through code? Something like this in my config file, but it can have multiple sections but not through appSettings as I would like to add multiple values to it. <configSections> <!-- CUSTOM CONFIG SECTIONS BELOW --> <section name="EmailSection" type="Email.EmailSection, Email" />...

Handle TimeoutReply message with Rebus configured with autofac

autofac,rebus
I'm trying out Rebus with the (external) timeoutservice. The TimeoutService correctly sends back a TimeoutReply. Then the subscriber logs an error that the TimeoutReplyHandler cannot be invoked. I'm using Autofac for dependency injection and use the following configuration to register the Handlers: ContainerBuilder builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()) .Where(t =>...

Call Service from Session_Start

asp.net-mvc-4,autofac,unit-of-work
I have an AuditService I created that looks like: public interface IAuditService { void Log(int userId, string obj, string action, string details); } In my controllers I can call the service like this: public class AccountController : BaseController { private readonly IAuditService _auditService; public AccountController(IUnitOfWork unitOfWork, IAuditService auditService) : base(unitOfWork)...

OWIN Service resolution Using Autofac

dependency-injection,web-api,autofac,owin
I have an WebApi application using OWIN and Autofac. Although controllers and parameters get resolved correctly, I would like to be able to use OwinContext.Get<type> to resolve types registered with Autofac. Is that posible? Already setapp.UseAutofacMiddleware(container); and config.DependencyResolver = new AutofacWebApiDependencyResolver(container); By example, I registered builder.Register<IAppConfiguration>(c => new AppConfig()); and...

ASP.NET MVC Autofac Singleton

asp.net-mvc,singleton,autofac
I am using autofac with ASP.NET MVC, using the Repository Pattern. I have a class like this public class IoC : ContainerBuilder { /// <summary> /// /// </summary> private readonly static IoC _instance = new IoC(); /// <summary> /// /// </summary> private static object _lock; /// <summary> /// /// </summary>...

Autofac integration with Mobile Azure Service

c#,autofac,azure-mobile-services
I have created Mobile Azure Service project and integrated it with the Autofac. Here is my IocConfig.cs in which I have registered all ApiControllers and libs. var containerBuilder = new ContainerBuilder(); //Register API controllers containerBuilder.RegisterApiControllers(typeof(UserController).Assembly); /*Register Libs*/ containerBuilder.RegisterType<UserLib>().As<IUserLib>(); /*Register ObjectContexts*/ containerBuilder.RegisterType<MobileServiceContext>() .As<DbContext>().InstancePerDependency(); var...

How to resolve component based on user context using Autofac

c#,asp.net-mvc,autofac
I have a service that requires a UserName to be passed in during construction. The UserName will come from the current web request either cookie or query string. builder.Register((c,p) => { var accessService = c.Resolve<IAccessService>(); var access = accessService.GetBySite(Request.QueryString["username"]); return new JsonWebRequest(access.Site, access.Token); }).InstancePerRequest(); I've tried to register as above...

What is the properusage of InstancePerOwned in autofac dependency injection

dependency-injection,inversion-of-control,autofac
I wanted to know what is the proper usage of InstancePerOwned() in Autofac. How can I use that when resolving dependencies?

How to use Autofac to inject specific implementation in constructor

c#,asp.net-mvc,dependency-injection,autofac
I have two classes that take a ILastActivityUpdator as a constructor parameter: UserService and AnonymousUserService. public AnonymousUserService(ILastActivityUpdator lastActivityUpdator) { if (lastActivityUpdator == null) { throw new ArgumentNullException("lastActivityUpdator"); } this.lastActivityUpdator = lastActivityUpdator; } And similar as above for UserService: public UserService(ILastActivityUpdator lastActivityUpdator) { if (lastActivityUpdator == null) { throw new ArgumentNullException("lastActivityUpdator");...

Is there a way to use AutoFac Web Api Authorization Filters through Attributes instead of injection?

asp.net-web-api,filter,dependency-injection,authorization,autofac
I have an Autofac Web Api Authorization Filter like that: public class MyAuthorizationFilter : IAutofacAuthorizationFilter { public void OnAuthorization(HttpActionContext actionContext){} } public class MyAuthorizationAttribute : Attribute { public MyAuthorizationAttribute() { } } Right now the only way I can have an Autofac Web Api Authorization Filter is through injecting it...

Masstransit InboundMessageInterceptor is in a different LifetimeScope to the Consumer

c#,autofac,masstransit
I have added my own headers into my messages and I need to process them to setup DB context for my consumer before the consumer is invoked (the headers allow me to setup my NHibernate session connected to the correct DB which I do not want to have to process...

AutoFac with WebApi, Still looking for parameter less constructor

asp.net-web-api,autofac
I have following class in my WebApi project and RegisterContainer() method gets called from Global.ASAX class. I am injecting Service in my api controller. The issue is it;s throwing exception and not getting instantiated corrected. It says No paremeterless Controller found. Any idea what's wrong with my code public class...

Property Injection with Autofac

c#,dependency-injection,asp.net-mvc-5,autofac,owin
I want to use Autofac for property injection. Here's my setup: public partial class Startup { public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<TeamManagerContext>().PropertiesAutowired(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); app.UseAutofacMiddleware(container); app.UseAutofacMvc(); ConfigureAuth(app); } } BaseController: public class...

Dynamic menu creation IoC

c#,inversion-of-control,autofac,ioc-container
I am wondering if anyone out there knows how I could create how could i use something like AutoFac to let me dynamically allow dll's to create there own forms and menu items to call them at run time. So if I have an, Employee.dll New Starter Form Certificate Form...

Registering ObservableCollection as self and as IEnumerable<> in Autofac causes circular dependency exception

c#,observablecollection,autofac,circular
I would like to have the same collection sometimes be visible as IEnumerable<T> and sometimes as ObservableCollection<T> but I get an Autofac error: Circular component dependency detected Here is my code: var builder = new ContainerBuilder(); builder.RegisterType<ObservableCollection<Foo>>() .InstancePerLifetimeScope() .AsSelf() .As<IEnumerable<Foo>>(); using (var containter = builder.Build()) { var foos = containter.Resolve<ObservableCollection<Foo>>();...

Module properties from xml, providing default values

c#,.net,autofac
If I have the following module: class MyModule : Module { public double SomeDouble { get; set; } } and I have the following autofac section in my app.config <autofac> <modules> <module type="MyNamespace.MyModule, MyNamespace"> <properties> <property name="SomeDouble" value="" /> </properties> </module> </modules> </autofac> When calling builer.Build() I get an exception...

Autofac registering all subtypes keyed according to a property

inversion-of-control,autofac
The following scenario: public enum ChildType { Type1, Type2, Type3 } public abstract class MyParentClass { public abstract ChildType Id { get; } } public class Child1 : MyParentClass { public override ChildType Id { get { return ChildType.Type1; } } } public class Child2 : MyParentClass { public override...

Autofac, dynamic dependency Injection for MVC controllers

asp.net-mvc,autofac
I have a project setup with UnitOfWork Interfaces and Managers. All this works well while I just had to use an accountMananger for the base of my controller. protected BaseController(IAccountManager acctManager) { _accountManager = acctManager; } and my controllers are created like this, and works. public class AccountController : BaseController...

Overriding AutoFac scoping configuration when using factory

c#,dependency-injection,autofac
How to configure AutoFac so that I get a new instance of Context every time I hit the factory. The Content component is set to InstancePerLifetimeScope(), which is perfect for 99% of my usage, but now I need a little extra control over how the Context component is scoped. class...

Autofac delegate factories, and passing around container

c#,dependency-injection,autofac
I have a question about delegate factories: autofac docs I understand how they set up the factories but I do not get the resolving part: var shareholdingFactory = container.Resolve<Shareholding.Factory>(); var shareholding = shareholdingFactory.Invoke("ABC", 1234); It looks like you have to pass around the container in order to resolve. Maybe I...

Autofac “action injection” with ASP.NET MVC model binding

c#,asp.net-mvc,autofac
I'm using Autofac with ASP.NET MVC and am wondering if my view model setup in the web project is a good approach or not. In the past I only used constructer injection at the Controller level but thought it would be interesting to see if everything could be injected via...

Compiler warning when using AuthorizationFilters with async method calls

c#,asynchronous,asp.net-web-api2,autofac
I have a fairly controller that requires login in before being able to do any other calls. I have an authorization filter setup to deny access to method without being authenticated, but I'm trying to setup an override for the login method. The issue is that the controller is using...

Automapper and Autofac

c#,autofac,automapper-3
I am trying to get Automapper to play nice with Autofac in an ASP.Net MVC application. I have followed the instructions in the answer to this: Autofac 3 and Automapper However it fails on the first call to _mapper.Map<>(...) Autofac is setup like this: builder.RegisterType<EntityMappingProfile>().As<Profile>(); builder.Register(ctx => new ConfigurationStore(new TypeMapFactory(),...