1) Autofac does not require any specific mapping of constructors. It has one simple rule; it will enter as much as it can, but it should be able to resolve all parameters of at least one constructor. If there are no constructors with parameter types that are all known by Autofac, you will get an exception at runtime. You can configure Autofac to install a constructor or property or a hybrid of both. The accepted best practice is for the constructor to introduce almost everything; using property injection can give you an object that does not have all the necessary dependencies that you donโt know about, until you try to use functionality that requires no dependency. If the dependency is expensive, it must be factory -scoped (a new instance for each request) and not always used by the dependent object, consider a constructor injecting a factory method that lazily initializes this dependency.
2) How to configure the IoC container depends on how you plan to use it. A static or single instance of an IoC container is certainly well-known, but many say itโs an anti-pattern, because it leads you to a slippery slope of using the container as a โservice locatorโ (which makes you dependent on having an IoC container to resolve your dependency Itโs nice, but not necessary). A common feature is the registration of all dependencies and all objects that need a dependency on the container, and the use of the container only at the highest level of creation of the object; all other objects will be dependent on the top-level object and either resolved as such, or can be obtained using the factory method.
I went ahead and installed the Autofac container as a singleton, since the container basically exists to remove an instance of the main form of the application, which itself needs most of the dependencies registered in IoC, and gets the rest anyway so that they can pass them to objects that he will create. I could register all objects using IoC and resolved child forms using factory methods, but I would replace dependency links with factory methods references, and I could probably connect individual methods in the main form as factories for other windows.
EDIT: sample code for 1):
public interface IDoSomething {...} public interface IDoSomethingElse {...}
source share