===================== Registration Concepts ===================== You register :doc:`components <../glossary>` with Autofac by creating a ``ContainerBuilder`` and informing the builder which :doc:`components <../glossary>` expose which :doc:`services <../glossary>`. **Components** can be created via **reflection** (by registering a specific .NET type or open generic); by providing a ready-made **instance** (an instance of an object you created); or via lambda **expression** (an anonymous function that executes to instantiate your object). ``ContainerBuilder`` has a family of ``Register()`` methods that allow you to set these up. Each component exposes one or more **services** that are wired up using the ``As()`` methods on ``ContainerBuilder``. .. sourcecode:: csharp // Create the builder with which components/services are registered. var builder = new ContainerBuilder(); // Register types that expose interfaces... builder.RegisterType().As(); // Register instances of objects you create... var output = new StringWriter(); builder.RegisterInstance(output).As(); // Register expressions that execute to create objects... builder.Register(c => new ConfigReader("mysection")).As(); // Build the container to finalize registrations // and prepare for object resolution. var container = builder.Build(); // Now you can resolve services using Autofac. For example, // this line will execute the lambda expression registered // to the IConfigReader service. using(var scope = container.BeginLifetimeScope()) { var reader = container.Resolve(); } .. _register-registration-reflection-components: Reflection Components ===================== Components generated by reflection are typically registered by type: .. sourcecode:: csharp var builder = new ContainerBuilder(); builder.RegisterType(); builder.RegisterType(typeof(ConfigReader)); When using reflection-based components, **Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container**. For example, say you have a class with three constructors like this: .. sourcecode:: csharp public class MyComponent { public MyComponent() { /* ... */ } public MyComponent(ILogger logger) { /* ... */ } public MyComponent(ILogger logger, IConfigReader reader) { /* ... */ } } Now say you register components and services in your container like this: .. sourcecode:: csharp var builder = new ContainerBuilder(); builder.RegisterType(); builder.RegisterType().As(); var container = builder.Build(); using(var scope = container.BeginLifetimeScope()) { var component = container.Resolve(); } When you resolve your component, Autofac will see that you have an ``ILogger`` registered, but you don't have an ``IConfigReader`` registered. In that case, the second constructor will be chosen since that's the one with the most parameters that can be found in the container. You can manually choose a particular constructor to use and override the automatic choice by registering your component with the ``UsingConstructor`` method and a list of types representing the parameter types in the constructor: .. sourcecode:: csharp builder.RegisterType() .UsingConstructor(typeof(ILogger), typeof(IConfigReader)); Note that you will still need to have the requisite parameters available at resolution time or there will be an error when you try to resolve the object. You can :doc:`pass parameters at registration time ` or you can :doc:`pass them at resolve time <../resolve/parameters>`. **An important note on reflection-based components:** Any component type you register via ``RegisterType`` must be a concrete type. While components can expose abstract classes or interfaces as :doc:`services <../glossary>`, you can't register an abstract/interface component. It makes sense if you think about it: behind the scenes, Autofac is creating an instance of the thing you're registering. You can't "new up" an abstract class or an interface. You have to have an implementation, right? Instance Components =================== In some cases, you may want to pre-generate an instance of an object and add it to the container for use by registered components. You can do this using the ``RegisterInstance`` method: .. sourcecode:: csharp var output = new StringWriter(); builder.RegisterInstance(output).As(); Something to consider when you do this is that Autofac :doc:`automatically handles disposal of registered components <../lifetime/disposal>` and you may want to control the lifetime yourself rather than having Autofac call ``Dispose`` on your object for you. In that case, you need to register the instance with the ``ExternallyOwned`` method: .. sourcecode:: csharp var output = new StringWriter(); builder.RegisterInstance(output) .As() .ExternallyOwned(); Registering provided instances is also handy when integrating Autofac into an existing application where a singleton instance already exists and needs to be used by components in the container. Rather than tying those components directly to the singleton, it can be registered with the container as an instance: .. sourcecode:: csharp builder.RegisterInstance(MySingleton.Instance).ExternallyOwned(); This ensures that the static singleton can eventually be eliminated and replaced with a container-managed one. The default service exposed by an instance is the concrete type of the instance. See "Services vs. Components," below. .. _register-registration-lambda-expression-components: Lambda Expression Components ============================ Reflection is a pretty good default choice for component creation. Things get messy, though, when component creation logic goes beyond a simple constructor call. Autofac can accept a delegate or lambda expression to be used as a component creator: .. sourcecode:: csharp builder.Register(c => new A(c.Resolve())); The parameter ``c`` provided to the expression is the *component context* (an ``IComponentContext`` object) in which the component is being created. You can use this to resolve other values from the container to assist in creating your component. **It is important to use this rather than a closure to access the container** so that :doc:`deterministic disposal <../lifetime/disposal>` and nested containers can be supported correctly. Additional dependencies can be satisfied using this context parameter - in the example, ``A`` requires a constructor parameter of type ``B`` that may have additional dependencies. The default service provided by an expression-created component is the inferred return type of the expression. Below are some examples of requirements met poorly by reflective component creation but nicely addressed by lambda expressions. Complex Parameters ------------------ Constructor parameters can't always be declared with simple constant values. Rather than puzzling over how to construct a value of a certain type using an XML configuration syntax, use code: .. sourcecode:: csharp builder.Register(c => new UserSession(DateTime.Now.AddMinutes(25))); (Of course, session expiry is probably something you'd want to specify in a configuration file - but you get the gist ;)) Property Injection ------------------ While Autofac offers :doc:`a more first-class approach to property injection `, you can use expressions and property initializers to populate properties as well: .. sourcecode:: csharp builder.Register(c => new A(){ MyB = c.ResolveOptional() }); The ``ResolveOptional`` method will try to resolve the value but won't throw an exception if the service isn't registered. (You will still get an exception if the service is registered but can't properly be resolved.) This is one of the options for :doc:`resolving a service <../resolve/index>`. **Property injection is not recommended in the majority of cases.** Alternatives like `the Null Object pattern `_, overloaded constructors or constructor parameter default values make it possible to create cleaner, "immutable" components with optional dependencies using constructor injection. Selection of an Implementation by Parameter Value ------------------------------------------------- One of the great benefits of isolating component creation is that the concrete type can be varied. This is often done at runtime, not just configuration time: .. sourcecode:: csharp builder.Register( (c, p) => { var accountId = p.Named("accountId"); if (accountId.StartsWith("9")) { return new GoldCard(accountId); } else { return new StandardCard(accountId); } }); In this example, ``CreditCard`` is implemented by two classes, ``GoldCard`` and ``StandardCard`` - which class is instantiated depends on the account ID provided at runtime. :doc:`Parameters are provided to the creation function <../resolve/parameters>` through an optional second parameter named ``p`` in this example. Using this registration would look like: .. sourcecode:: csharp var card = container.Resolve(new NamedParameter("accountId", "12345")); A cleaner, type-safe syntax can be achieved if a delegate to create ``CreditCard`` instances is declared and :doc:`a delegate factory <../advanced/delegate-factories>` is used. Open Generic Components ======================= Autofac supports open generic types. Use the ``RegisterGeneric()`` builder method: .. sourcecode:: csharp builder.RegisterGeneric(typeof(NHibernateRepository<>)) .As(typeof(IRepository<>)) .InstancePerLifetimeScope(); When a matching service type is requested from the container, Autofac will map this to an equivalent closed version of the implementation type: .. sourcecode:: csharp // Autofac will return an NHibernateRepository var tasks = container.Resolve>(); Registration of a specialized service type (e.g. ``IRepository``) will override the open generic version. Services vs. Components ======================= When you register :doc:`components <../glossary>`, you have to tell Autofac which :doc:`services <../glossary>` that component exposes. By default, most registrations will just expose themselves as the type registered: .. sourcecode:: csharp // This exposes the service "CallLogger" builder.RegisterType(); Components can only be :doc:`resolved <../resolve/index>` by the services they expose. In this simple example it means: .. sourcecode:: csharp // This will work because the component // exposes the type by default: scope.Resolve(); // This will NOT work because we didn't // tell the registration to also expose // the ILogger interface on CallLogger: scope.Resolve(); You can expose a component with any number of services you like: .. sourcecode:: csharp builder.RegisterType() .As() .As(); Once you expose a service, you can resolve the component based on that service. Note, however, that once you expose a component as a specific service, the default service (the component type) is overridden: .. sourcecode:: csharp // These will both work because we exposed // the appropriate services in the registration: scope.Resolve(); scope.Resolve(); // This WON'T WORK anymore because we specified // service overrides on the component: scope.Resolve(); If you want to expose a component as a set of services as well as using the default service, use the ``AsSelf`` method: .. sourcecode:: csharp builder.RegisterType() .AsSelf() .As() .As(); Now all of these will work: .. sourcecode:: csharp // These will all work because we exposed // the appropriate services in the registration: scope.Resolve(); scope.Resolve(); scope.Resolve(); Default Registrations ===================== If more than one component exposes the same service, **Autofac will use the last registered component as the default provider of that service**: .. sourcecode:: csharp builder.Register().As(); builder.Register().As(); In this scenario, ``FileLogger`` will be the default for ``ILogger`` because it was the last one registered. To override this behavior, use the ``PreserveExistingDefaults()`` modifier: .. sourcecode:: csharp builder.Register().As(); builder.Register().As().PreserveExistingDefaults(); In this scenario, ``ConsoleLogger`` will be the default for ``ILogger`` because the later registration for ``FileLogger`` used ``PreserveExistingDefaults()``. Configuration of Registrations ============================== You can :doc:`use XML or programmatic configuration ("modules") <../configuration/index>` to provide groups of registrations together or change registrations at runtime. You can also use :doc:`use Autofac modules <../configuration/modules>` for some dynamic registration generation or conditional registration logic. Dynamically-Provided Registrations ================================== :doc:`Autofac modules <../configuration/modules>` are the simplest way to introduce dynamic registration logic or simple cross-cutting features. For example, you can use a module to :doc:`dynamically attach a log4net logger instance to a service being resolved <../examples/log4net>`. If you find that you need even more dynamic behavior, such as adding support for a new :doc:`implicit relationship type <../resolve/relationships>`, you might want to :doc:`check out the registration sources section in the advanced concepts area <../advanced/registration-sources>`.