Adding dependencies that don’t implement IDependency to Orchard

There are rare cases where you’ll want to be able to inject instances of classes that don’t implement IDependency. One example of this can be found in MvcModule in Orchard.Framework, which also provides a good example of how to do it. The idea is to derive from Module, and override the Load method to register factories for the types you want to expose:

protected override void Load(ContainerBuilder moduleBuilder) {
moduleBuilder
.Register(TheTypeFactory)
.As<TheType>
.InstancePerDependency();
}

The call to InstancePerDependency is declaring the scope of the instance. It can be replaced with any other Instance* method, depending on the lifetime you want for the instances.

Each factory is a static method that can return an instance from the Autofac.IComponentContext instance that will get passed as a parameter:

static TheType TheTypeFactory(IComponentContext context)

The context object provides a method to resolve instances already in the component registry. And that’s pretty much it…

No Comments