Using Run Time Configuration
This topic discusses some of the factors you should keep in mind when using run-time configuration, and explains some features of the Unity run-time configuration mechanism. For details on how to specify configuration using a configuration file, see Design-Time Configuration.
The API for the Unity container provides a fluent configuration interface which enables you to chain method calls in one statement. To use the fluent interface, call all the methods you want, one after the other, in a single statement, as shown in the following code.
IUnityContainer myContainer = new UnityContainer() .RegisterType<IMyService, DataService>() .RegisterType<IMyService, EmailService>() .RegisterType<MyServiceBase, LoggingService>();
Method chaining is not a requirement, but it does expedite coding by relieving you from repeatedly typing "container." You can use this approach to chain any of the methods of the UnityContainer class when you create the container. For example, you can use any combination of the RegisterType, RegisterInstance, AddExtension, and Configure methods to prepare the container.
Extensions use the Configure method of the container to provide access to a configuration interface for the extension. Many extensions expose a fluent interface that makes it easier to configure the features of that extension. For example, interception is implemented as a container extension and exposes the AddPolicy method that you use to define an interception policy at run time. You specify the type of matching rule, MatchingRuleType, and type of call handler, HandlerType.
IUnityContainer myContainer = new UnityContainer() .AddNewExtension<Interception>() .Configure<Interception>() .AddPolicy("PolicyName") .AddMatchingRule<MatchingRuleType>() .AddCallHandler<HandlerType>() .Container;
|When using Visual Basic, you should use the full syntax for declaring the container, as shown in the previous code example. The fluent interface methods all return IUnityContainer, not UnityContainer. If you use the short syntax Dim myContainer As New UnityContainer(), the fluent interface mechanism will result in a type mismatch and compile errors.|