<commit_before>=====================
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<ConsoleLogger>.As<ILogger>();

    // Register instances of objects you create...
    var output = new StringWriter();
    builder.RegisterInstance(output).As<TextWriter>();

    // Register expressions that execute to create objects...
    builder.Register(c => new ConfigReader("mysection")).As<IConfigReader>();

    // 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<IConfigReader>();
    }

.. _register-registration-reflection-components:

Reflection Components
=====================

Components generated by reflection are typically registered by type:

.. sourcecode:: csharp

    var builder = new ContainerBuilder();
    builder.RegisterType<ConsoleLogger>();
    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<MyComponent>();
    builder.RegisterType<ConsoleLogger>().As<ILogger>();
    var container = builder.Build();

    using(var scope = container.BeginLifetimeScope())
    {
      var component = container.Resolve<MyComponent>();
    }

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<MyComponent>()
           .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 <parameters>` 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<TextWriter>();

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<TextWriter>()
           .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:<commit_msg>Minor reorg for reflection docs<commit_after>=====================
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<ConsoleLogger>.As<ILogger>();

    // Register instances of objects you create...
    var output = new StringWriter();
    builder.RegisterInstance(output).As<TextWriter>();

    // Register expressions that execute to create objects...
    builder.Register(c => new ConfigReader("mysection")).As<IConfigReader>();

    // 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<IConfigReader>();
    }

.. _register-registration-reflection-components:

Reflection Components
=====================

Register by Type
----------------

Components generated by reflection are typically registered by type:

.. sourcecode:: csharp

    var builder = new ContainerBuilder();
    builder.RegisterType<ConsoleLogger>();
    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<MyComponent>();
    builder.RegisterType<ConsoleLogger>().As<ILogger>();
    var container = builder.Build();

    using(var scope = container.BeginLifetimeScope())
    {
      var component = container.Resolve<MyComponent>();
    }

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.

**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?

Specifying a Constructor
------------------------

**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<MyComponent>()
           .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 <parameters>` or you can :doc:`pass them at resolve time <../resolve/parameters>`.

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<TextWriter>();

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<TextWriter>()
           .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:
{'fraction_non_alphanumeric': 0.10209190059002324, 'fraction_numerical': 0.0, 'mean_word_length': 4.1292984869325995, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2612083', 'n_tokens_mistral': 2650, 'n_tokens_neox': 2542, 'n_words': 1265}