EnterLib ObjectBuild vs Castle WindsorContainer, part 1

Source: Internet
Author: User
First, let's take a look at a small example in the Castle project to demonstrate its Ioc function:

   1:  public interface IEmailSender
   2:  {
   3:      void Send(String from, String to, String message);
   4:  }
   5:   
   6:  public interface ITemplateEngine
   7:  {
   8:      String Process(String templateName);
   9:  }
  10:   
  11:  public interface INewsletterService
  12:  {
  13:      void Dispatch(String from, String[] targets, String message);
  14:  }
  15:   
  16:  public class SmtpEmailSender : IEmailSender
  17:  {
  18:      private String _host;
  19:      private int _port;
  20:   
  21:      public SmtpEmailSender(String host, int port)
  22:      {
  23:          _host = host;
  24:          _port = port;
  25:      }
  26:   
  27:      public virtual void Send(String from, String to, String message)
  28:      {
  29:          Console.WriteLine("Sending e-mail from {0} to {1} with '{2}'", 
  30:              from, to, message );
  31:      }
  32:  }
  33:   
  34:  public class NVelocityTemplateEngine : ITemplateEngine
  35:  {
  36:      public virtual String Process(String templateName)
  37:      {
  38:          return "Some template content";
  39:      }
  40:  }
  41:   
  42:  public class SimpleNewsletterService : INewsletterService
  43:  {
  44:      private IEmailSender _sender;
  45:      private ITemplateEngine _templateEngine;
  46:   
  47:      public SimpleNewsletterService
  48:          (IEmailSender sender, ITemplateEngine templateEngine)
  49:      {
  50:          _sender = sender;
  51:          _templateEngine = templateEngine;
  52:      }
  53:   
  54:      public void Dispatch(String from, String[] targets, String message)
  55:      {
  56:          String msg = _templateEngine.Process(message);
  57:   
  58:          foreach(String target in targets)
  59:          {
  60:              _sender.Send(from, target, msg);
  61:          }
  62:      }
  63:   
  64:  }

The function of Ioc is to automatically create a SimpleNewsletterService object by using the container, instead of directly creating and passing its parameters, which further reduces the coupling between the object and the object, so as to conveniently replace its implementation. In the preceding example, the constructor sets the value to inject object dependencies. The following describes how to implement Castle:

BasicUsage. xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Components>
<Component id = "smtpemailsender">
<Parameters>
<Host> localhost <Port> 110 </port>
</Parameters>
</Component>
</Components>
</Configuration>

   1:  public static void Main()
   2:  {
   3:      IWindsorContainer container = 
   4:      new WindsorContainer( new XmlInterpreter("../BasicUsage.xml") );
   5:   
   6:      container.AddComponent( "newsletter", 
   7:          typeof(INewsletterService), typeof(SimpleNewsletterService) );
   8:      container.AddComponent( "smtpemailsender", 
   9:          typeof(IEmailSender), typeof(SmtpEmailSender) );
  10:      container.AddComponent( "templateengine", 
  11:          typeof(ITemplateEngine), typeof(NVelocityTemplateEngine) );
  12:   
  13:      String[] friendsList = new String[] { "john", "steve", "david" };
  14:   
  15:      // Ok, start the show
  16:   
  17:      INewsletterService service = 
  18:          (INewsletterService) container["newsletter"];
  19:      service.Dispatch("hammett at gmail dot com",
  20:                                friendsList, "merryxmas");
  21:  }

Constantly add various types of objects to the container. During the adding process, the container Automatically Establishes dependencies between them. Finally, when we retrieve objects from the container, is the object with dependency configured. The above is the working mode of Castle, but the configuration process in Castle is too transparent. If you don't expect it, the object dependency is set according to the order in which the object is injected into the container. It is very automatic and transparent, and sometimes it is inexplicable.

Let's take a look at the implementation method of ObjectBuild. First, you need to explicitly set the dependency through the attribute (attivity) or configuration file:

  42:  public class SimpleNewsletterService : INewsletterService
  43:  {
  44:      private IEmailSender _sender;
  45:      private ITemplateEngine _templateEngine;
  46:   
  47:      public SimpleNewsletterService(
  48:              [Dependency(CreateType = typeof(SmtpEmailSender))]
  49:              IEmailSender sender, 
  50:              [Dependency(CreateType = typeof(NVelocityTemplateEngine))] 
  51:              ITemplateEngine templateEngine)
  52:      {
  53:          _sender = sender;
  54:          _templateEngine = templateEngine;
  55:      }
  56:   
  57:      public void Dispatch(String from, String[] targets, String message)
  58:      {
  59:          String msg = _templateEngine.Process(message);
  60:   
  61:          foreach(String target in targets)
  62:          {
  63:              _sender.Send(from, target, msg);
  64:          }
  65:      }
  66:   
  67:  } 

 

Then, use Build to construct the object directly.

Public static void Main (string [] args)
{
String config = string. Format (
@ "<Object-builder-config xmlns = 'pag-object-builder'>
<Build-rules>
<Build-rule type = '{0}' mode = 'singleton'>
<Mapped-type = '{1}'/>
<Constructor-params>
<Value-param type = 'System. string'> localhost </value-param>
<Value-param type = 'System. int3'> 110 </value-param>
</Constructor-params>
</Build-rule>
</Build-rules>
</Object-builder-config> ", FullNameIEmailSender, FullNameSmtpEmailSender );

Builder builder = new Builder (ObjectBuilderXmlConfig. FromXml (config ));
Locator locator = CreateLocator ();

INewsletterService newsletterService =
Builder. BuildUp <SimpleNewsletterService> (locator, null, null );

String [] friendsList = new String [] {"john", "steve", "david "};

// OK, start the show

NewsletterService. Dispatch ("hammett at gmail dot com ",
FriendsList, "merryxmas ");
}

From the above we can see that
1. ObjectBuild is similar to Sping, and dependency needs to be explicitly specified, but Attribute is used to specify more methods, while Castle depends on the specific object injection sequence. It can be said that each has its own advantages and disadvantages, but I prefer the former, security first. (Castle also provides explicitly specified methods in the configuration file .)
2. ObjectBuild supports creating temporary objects without injecting containers. (Note that in the above Code, we only BuildUp the SimpleNewsletterService, but we do not need to inject the objects on which SimpleNewsletterService is dependent into the container like Castle .) In fact, you can choose whether to inject objects into the container in OB. Normally, Singleton objects are injected into the container.
3. compared with the Castle container concept, ObjectBuild is shown in its name. It is more like a builder. You can use it to build any objects that may be injected into the container, it may also be just a temporary object, but you can add a lot of control in the object creation process to make it more in line with your needs.
4. comparatively speaking, Castle Ioc is more concise to use, while ObjectBuild is more complex (in fact, compared with the statements required for building objects, OB requires less, but OB APIs are not concise enough, but the custom extension capability of ObjectBuild is also quite powerful. For example, the preceding configuration method combined with the configuration file and Attribute, it can be done through the APIS provided in OB. The following describes how to implement full programming:
Public static void Main ()
{

Builder builder = new Builder ();
Locator locator = CreateLocator ();

Builder. Policies. SetDefault <ISingletonPolicy> (new SingletonPolicy (true ));

ConstructorPolicy policy = new ConstructorPolicy ();
Policy. AddParameter (new ValueParameter <string> ("localhost "));
Policy. AddParameter (new ValueParameter <int> (110 ));

Builder. Policies. Set <ICreationPolicy>
(Policy, typeof (SmtpEmailSender), null );
Builder. Policies. Set <ITypeMappingPolicy>
(New TypeMappingPolicy (typeof (SmtpEmailSender), null ),
Typeof (IEmailSender), null );

Builder. Policies. Set <ITypeMappingPolicy>
(New TypeMappingPolicy (typeof (NVelocityTemplateEngine), null ),
Typeof (ITemplateEngine), null );

ConstructorPolicy using y2 = new ConstructorPolicy ();
Policy2.AddParameter (new CreationParameter (typeof (IEmailSender )));
Policy2.AddParameter (new CreationParameter (typeof (ITemplateEngine )));
Builder. Policies. Set <ICreationPolicy>
(Optional Y2, typeof (SimpleNewsletterService), null );

INewsletterService newsletterService =
Builder. BuildUp <SimpleNewsletterService> (locator, null, null );

String [] friendsList = new String [] {"john", "steve", "david "};

// OK, start the show

NewsletterService. Dispatch ("hammett at gmail dot com ",
FriendsList, "merryxmas ");
}

5. Both Castle Ioc and ObjectBuild support the Property Setter injection method.

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.