I am using the constructor constructor of Autofac. I need to figure out how to insert an instance of one object into several constructor arguments, without having to explicitly resolve each argument during the container configuration phase.
I have a complex scenario that will be simplified by this behavior; The following example is just a simplified scenario, so I can demonstrate the behavior I'm looking for.
Example:
Let's say I have these two interfaces: IOpenable and ICloseable:
public interface IOpenable { void Open(); } public interface ICloseable { void Close(); }
And I have this Door class that implements both of them:
public interface IDoor : IOpenable, ICloseable { } public class Door : IDoor, IOpenable, ICloseable { void Open() { ... } void Close() { ... } }
And I have this class that accepts IOpenable and ICloseable:
public class DoorHandler : IDoorHandler { public DoorHandler(IOpenable openable, ICloseable closeable) { ... } ... }
Question:
Is it possible to tell autofac to insert the same Door object into both arguments when both IOpenable and ICloseable are dependencies in the same constructor?
Note. I can not do :
container.Register<IDoorHandler>( c => { Door d = c.Resolve<IDoor>(); return new DoorHandler(d,d) });
This will do what I want, but remember that this DoorHandler class is just an example. In my real code, the βDoorHandlerβ is indeed an MVC controller, and I am registering it with RegisterControllers (). Therefore, I cannot register it as indicated above. In addition, sometimes dependency graphs can be overly complex, and this clearly can be overwhelming in each case.
I assume that I am looking to be able to do something like:
container.RegisterType<DoorHandler>().As<IDoorHandler>(); container.RegisterType<Door>().As<IDoor>(); container.Register<IOpenable>( c => c.ResolveShared<IDoor>(); ); container.Register<ICloseable>( c => c.ResolveShared<IDoor>(); );
when calls to c.ResolveShared<T> will be resolved to the same T object if more than one argument is called in the same constructor.
Or perhaps:
container.RegisterType<DoorHandler>().As<IDoorHandler>(); container.RegisterType<Door>().As<IDoor>().InstancePerDependencyShared(); container.Register<IOpenable>( c => c.Resolve<IDoor>(); ); container.Register<ICloseable>( c => c.Resolve<IDoor>(); );
Obviously, if I used InstancePerLifetimeScope or something for the Door object, each resolved Door would be the same instance. But I do not want this, I want each DoorHandler instance to create a new door instance, and I want this Door to be passed as both arguments to the DoorHandler constructor.