Ninject Tour: Ninject dynamic factory (download with program)

Source: Internet
Author: User

Summary

If we already know all the dependencies of a class, it is easy to introduce a series of dependencies in the class's constructor in the scenario where we only need an instance of the dependency. But in some cases, we need to create multiple instances of dependencies in a class, when ninject injection is not enough. In some cases, we don't know which service a consumer might need, because he might need different services on different occasions, and it would be unreasonable to instantiate all the dependencies when creating the class. In this case, the dynamic factory can help. We can design our class so that he relies on a factory rather than relying on objects that the factory can create. We can then command the factory to create the required type and any quantity required by command. The following two examples solve the above two problems. Ninject Dynamic Factory Creates a specified number of dependencies and creates a dependency of the specified type.

This article only describes the Ninject dynamic factory creating a specified number of dependencies, and the next article describes Ninject dynamic factory creation of a specified type of dependency.

Attached: Code download

Example: Shape factory

In the first example, we will create a graphical dynamic library. It contains a Shapservice class that provides a Addshapes method to add a specified number of specific IShape objects to the specified Icanvas object:

1      Public voidAddshapes (intCirclesintsquares, Icanvas canvas)2     {3          for(inti =0; I < circles; i++)4         {5             varCircle =NewCircle ();6 Canvas. Addshap (circle);7         }8          for(inti =0; i < squares; i++)9         {Ten             varSquare =NewSquare (); One Canvas. Addshap (square); A         } -}

The traditional approach is to create new instances of circle and square classes directly in the Addshapes method. However, this method coupled the Shapservice class with the specific circle and square classes, as opposed to the DI principle. In addition, the introduction of these dependencies by parameters does not meet our needs, as it is not enough for a shape to inject only one instance. To solve this problem, we should first create a simple factory interface like this:

1  Public Interface ishapefactory 2 {3    icircle createcircle (); 4     ISquare createsquare (); 5 }

We can then introduce this factory interface as a dependency of the Shapeservice class.

1      Public classShapeservice2     {3         Private ReadOnlyishapefactory _factory;4 5          PublicShapeservice (ishapefactory Factory)6         {7              This. _factory =Factory;8         }9 Ten          Public voidAddshapes (intCirclesintsquares, Icanvas canvas) One         { A              for(inti =0; I < circles; i++) -             { -                 varCircle =_factory. Createcircle (); the Canvas. Addshap (circle); -             } -              for(inti =0; i < squares; i++) -             { +                 varSquare =_factory. Createsquare (); - Canvas. Addshap (square); +             } A         } at}

The good news is that we don't have to worry about how to achieve ishapefactory. Ninject is able to implement it dynamically, and then inject this implementation into the factory into this shapeservice class. We just need to add the following code to our type Registration section:

1 bind<ishapefactory>(). Tofactory (); 2 bind<isquare> (). To<square>
3 bind<icircle> (). To<circle> ();

In order to use the Ninject factory, we need to add a reference to the Ninject.Extensions.Factory dynamic library. Can be added via NuGet or downloaded from the Ninject official website.

Remember that the factory can have as many methods as needed, and each method can return any desired type. These methods can have arbitrary names and have any number of arguments. The only limitation is that the name and argument type must match the type of the specific class name and constructor parameter, but it doesn't matter in their order. Even if the number of parameters does not need to be consistent, Ninject will try to parse the parameters that are not provided through the factory interface.

So, if the specific square class is the following:

1  Public class Square 2 {3      Public Square (Point startPoint, point EndPoint) 4     { ... } 5 }

This ishapefactory factory interface should look like this:

1  Public Interface ishapefactory 2 {3    icircle createcircle (); 4     ISquare createsquare (Point startPoint, point endPoint); 5 }

Alternatively, the Createsquare method might look like this:

1 ISquare createsquare (Point endPoint, point StartPoint);

This is the default behavior of the Ninject dynamic factory. However, by creating a custom instance provider, the default behavior can be overridden. The following article is going to introduce this.

It is slightly different for a dynamic factory to register a contract-based binding and a regular contract binding. The difference is that once we select the assembly, we should select the service type instead of the component and then bind them to the factory. The following describes how to implement these two steps.

    1. Select service Type

Use the following method to select an abstract class or interface:

    • Selectallincludingabstractclasses (): This method selects all classes, including abstract classes.
    • Selectallabstractclasses (): This method selects only abstract classes.
    • Selectallinterfaces (): This method selects all interfaces.
    • Selectalltypes (): This method selects all types (classes, interfaces, structs, common and primitive types)

The following code binds all interfaces under the selected assembly to the dynamic factory:

1     Kernel. Bind (x = x2     . Fromassembliesmatching ("factories")3    . Selectallinterfaces ()4     . Bindtofactory ());

2. Defining the binding generator

Use the following method to define the appropriate binding generator:

    • Bindtofactory: This method registers the type of mapping as a dynamic factory.
    • Bindwith: This method creates a binding using the binding builder parameter. Creating a binding generator is just a matter of implementing the Ibindinggenerator interface

The following example binds all of the interfaces in the current assembly that end with factory to the dynamic factory.

1     Kernel. Bind (x = x2    . fromthisassembly ()3    . Selectallinterfaces ()4     . Endingwith ("Factory")5     . Bindtofactory ());

Ninject Tour: Ninject dynamic factory (download with program)

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.