Getting Started

   using Grace.DependencyInjection;

   DependencyInjectionContainer container = new DependencyInjectionContainer();

   container.Configure(c => c.Export<BasicService>().As<IBasicService>());

   IBasicService basicService = container.Locate<IBasicService>();


Above is the simplest example of using the dependency injection container. It can be broken down into three steps
  • Create the container
  • Configure the container
  • Locate exports from the container

Container Creation

The container has one constructor that has 3 optional parameters
  • environment - A container operates in one of three environments (RunTime, UnitTest, DesignTime). This value is used to sort multiple exports as well as to filter exports for particular environments. By default its RunTime
  • comparer - The Comparer is used to sort multiple exports for order, by default DependencyInjectionContainer.CompareExportStrategies is used
  • disposalScopeProvider - If you want to provide custom disposal scopes for InjectionContexts you can provide this parameter, by default the IInjectionScope is used as the disposal scope

Configuration

When configuring the container you have a choice to make up front. Do you want to use the Fluent Interface to configure the container or do you want to use attributes (similar to MEF)
  • Fluent Configuration - Using this method you register class individually or in bulk using the fluent interface. Above is an example of registering one type using the fluent interface
  • Attribute Configuration - Using this method you apply attributes to your class that direct the container on how to configure and export your type.

Note: You can do both attribute and fluent in the same container, it's really up to you how you want to put your application together

Location

Now it's time to locate an export, you have two choices Locate and LocateAll.
  • Locate - Locates a single instance by either name or Type, there are multiple overloads with optional parameters for each to allow you the greatest flexibility over which exports you construct. When there are multiple exports by the name or type they are sorted based on Environment then priority and the first one meeting conditions will be returned.
  • LocateAll - Locates a collection of exports, if no filter is provided all exports that meet the conditions for exporting will be included in the return set. When locating by Type you can use the generic overload which returns back an IEnumerable<T> versus the IEnumerable<object> returned by other overloads.

Note: There are a set of C# extensions for LocateByKey for locating when an export was registered with a key but they are just wrappers around Locate using the filtering ability of Locate.

Advanced Topics

Import Special Types
InjectionContext
Child Scopes
API Documentation

Last edited Dec 14, 2013 at 4:30 AM by ipjohnson123, version 16