AUTOFAC Official document (16) "Run Code at startup"

Source: Internet
Author: User

AUTOFAC provides the ability to notify components or automatically activate components when building a container.

There are three types of automatic activation mechanisms available:-bootable component-automatic activation component-Container build callback

In all cases, the component will be activated when the container is built. components that can be started

A bootable component is a component that the container activates at the time of the initial build, and a specific method is invoked to boot an action on the component.

The key is to implement the Autofac.istartable interface. When the container is built, the component is activated and the Istartable.start () method is invoked.

This occurs only once, and for the first time, a container is built for a single instance of each component. Manually resolving a bootable component does not cause the start () method to be invoked. It is not recommended that you start a component to implement another service, or register as any other service other than SingleInstance ().

A component like the start () method should be used every time it is activated to use a survival event such as onactivated.

To create a bootable component, implement autofac.istartable:

public class startupmessagewriter:istartable
{public
   void Start ()
   {
      Console.WriteLine ("App Starting up! ");
   }
}

Then register your component and make sure it is specified as istartable, otherwise the operation will not be invoked:

var builder = new Containerbuilder ();
Builder
   . Registertype<startupmessagewriter> ()
   . As<istartable> ()
   . SingleInstance ();

When you build the container, the type is activated and the Istartable.start () method is invoked. In this example, a message is written to the console.

Known issues: Although the istartable component will be resolved in dependency order, the start () method may not actually be invoked in dependency order. You can use a container that combines with singleinstance registration to build callbacks to resolve this issue. See below. components that are automatically activated

An automatically activated component is a component that only needs to be activated once when the container is built. This is a "hot start" behavior in which any method of a component is not invoked, nor does it need to implement an interface-a single instance of a component is parsed without involving the instance it holds.

To register an automatically activated component, use AutoActivate () to register the extension.

var builder = new Containerbuilder ();
Builder
   . Registertype<typerequiringwarmstart> ()
   . Asself ()
   . AutoActivate ();

Note: If you omit the asself () or as<t> () service registration call while registering the AutoActivate () component, the component will only be registered for automatic activation, and the container will not necessarily parse itself after it is built. Container Build Callback

You can register any action that occurs when the container is built by registering the build callback. The build callback is a action<icontainer> and gets the constructed container before returning the container from Containerbuilder.build. Build callbacks are executed in the order in which they are registered:

var builder = new Containerbuilder ();
Builder
   . Registerbuildcallback (c => c.resolve<dbcontext> ());

/callback will run
var container = Builder After the container is generated but before it returns. Build ();

You can use the build callback as an alternative way to automatically start/Preheat objects in a container build. This is done by using them in conjunction with lifecycle event onactivated and singleinstance registration. This resolves known issues that the istartable implementation resolves in a dependent order, but the start () method is not necessarily called in dependent order.

A lengthy/artificial example in the form of unit tests:

public class TestClass {//Create a dependency chain like://==> 2 ==+//4 =+ ==> 1//==> 3 ==+//4 2 and 3 2 need 1//3 need 1//dependencies should be started in sequence//1, 2, 3, 4///1, 3, 2, 4 private class Dependency1 {public Dep Endency1 (itestoutputhelper output) {output.
    WriteLine ("Dependency1.ctor");

    } private class Dependency2 {private itestoutputhelper output;
      Public Dependency2 (Itestoutputhelper output, Dependency1 dependency) {this.output = output; Output.
    WriteLine ("Dependency2.ctor");
    public void Initialize () {this.output.WriteLine ("dependency2.initialize");

    } private class Dependency3 {private itestoutputhelper output;
      Public Dependency3 (Itestoutputhelper output, Dependency1 dependency) {this.output = output; Output.
    WriteLine ("Dependency3.ctor");
    public void Initialize () {this.output.WriteLine ("dependency3.initialize");

}
  }  Private class Dependency4 {private itestoutputhelper output; Public Dependency4 (itestoutputhelper output, Dependency2 dependency2, Dependency3 dependency3) {this.output = O
      Utput; Output.
    WriteLine ("Dependency4.ctor");
    public void Initialize () {this.output.WriteLine ("dependency4.initialize");
  }//xunit passes this to the ctor of the test class, so we can capture the console output.

  Private Itestoutputhelper _output;
  Public TestClass (Itestoutputhelper output) {this._output = output;
    [Fact] public void Onactivateddependencychain () {var builder = new Containerbuilder (); Builder. RegisterInstance (This._output).
    As<itestoutputhelper> (); Builder. Registertype<dependency1> ().

    SingleInstance (); Onactivated replaces the need for istartable. When an instance is activated/created, it runs the Initialize method in the way specified.
    The use of singleinstance means that it occurs only once. Builder. Registertype<dependency2> (). SingleInstance (). onactivated (args => args.
    Instance.initialize ()); Builder. Registertype<dependeNcy3> (). SingleInstance (). onactivated (args => args.
    Instance.initialize ()); Builder. Registertype<dependency4> (). SingleInstance (). onactivated (args => args.

    Instance.initialize ()); Note that these are not dependency order builder.
    Registerbuildcallback (c => c.resolve<dependency4> ()); Builder.
    Registerbuildcallback (c => c.resolve<dependency2> ()); Builder.
    Registerbuildcallback (c => c.resolve<dependency1> ()); Builder.

    Registerbuildcallback (c => c.resolve<dependency3> ());
    This will run the build callback. var container = Builder.

    Build (); These do not have any effect.
    Onactivated will not be invoked again because they are singleinstance. Container.
    Resolve<dependency1> (); Container.
    Resolve<dependency2> (); Container.
    Resolve<dependency3> (); Container.
  Resolve<dependency4> (); }
}

This sample unit test produces this output:

Dependency1.ctor
dependency2.ctor
dependency3.ctor
dependency4.ctor
dependency2.initialize
dependency3.initialize
Dependency4.initialize

You will see from the output that the callback function and the Onactivated method are executed in a dependent order. If you have to have both activation and startup occur in a dependency order (not just activation/resolution), this is the solution.

Note that if you do not use SingleInstance, onactivated will be invoked for each new dependency instance. Because the hot start object is usually a single case, it is expensive to create, so this is usually what you want.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.