Skip to content

Fluent Configuration

Ian Johnson edited this page Feb 17, 2017 · 15 revisions

The fluent interface has a number of different ways to export types and assemblies for export.

  • Export<T>() - used to export a single type for one or more interfaces. Because this method is generic it allows for lambdas to be used to specify importing of properties and method.
  container.Configure(c => c.Export<SomeType>().As<ISomeInterface>());

  • Export(Type type) - used to export a single type when it's not possible to use the Generic interface. One reason to use this method would be to register an open generic type, another use could be that you don't know the type you are going to register till runtime
  container.Configure(c => c.Export(typeof(SomeType)).As(typeof(ISomeInterface)));

  • Export(IEnumerable types) - used to register multiple types in one pass. Grace provides a very rich interface for exporting many classes at a time. Using Select and Exclude you can decide which types to export as well as many other options to help automate registration.
  container.Configure(c => c.Export(Types.FromThisAssembly()).
                             ByInterfaces().
                             Select(TypesThat.HaveAttribute<SomeAttribute>().Or.
                                              HaveAttribute<OtherAttribute>()));

Note: Types.FromThisAssembly() is in the Grace.Net package


  • Linq Bulk Configuration - If you are more comfortable with Linq you can use it to select which Types to export and then configure the exports.
DependencyInjectionContainer container = new DependencyInjectionContainer();

container.Configure(c => (from type in Types.FromThisAssembly() 
                          where type.Namespace.Contains("Simple")
                          select type)
                         .ExportTo(c)
                         .ByInterfaces());

  • ExportInstance<T>(ExportFunction<T> instanceFunction) - using this method you can provide a function that will be used to export rather than allowing the framework to compile a delegate for export.
  container.Configure(c => c.ExportInstance(
                             (scope,context) => new SomeType()).As<ISomeInterface>());

  • ExportInstance<T>(T instance) - this method can be used to export a specific instance under a particular interface or name.
  container.Configure(c => c.ExportInstance(someInstance).As<ISomeInterface>());

  • AddExportStrategy(IExportStrategy exportStrategy) - this method allows the developer to provide their own export strategies to the container. Most developers will never need to use this but it's here just incase.
  container.Configure(c => c.AddExportStrategy(exportStrategy));
Clone this wiki locally