Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

4/10/2015 IDeliverable 

­ Autofac.Module

Autofac.Module
orchard (/Tags/orchard) autofac (/Tags/autofac)

Although Autofac is not really part of Orchard's public API, it does

come in handy when you need to customize how some of your

classes are created and managed by Autofac.

In general, when you write your own classes that are injectable, you would take the following
steps:

1. Define an interface that derives from IDependency;


2. Define a class that implements your interface

However, in certain cases, you may want to inject concrete classes directly into your constructor
instead of an interface. One example might be when you implement the Command Pattern
(http://www.codeproject.com/Articles/12263/The-Command-Pattern-and-MVC-Architecture). You
would generally have multiple classes that ultimately implement some ICommand interface.
Next, consider having a controller that has a dependency on some command, e.g.
SaveCustomerCommand. One solution could be to create a specific interface for each command,
which would be perfectly fine (and perhaps even preferrable for unit testing classes that depend
on these commands). But let's say that for some reason you don't want to write these interfaces.
How would you be able to inject an UpdateCustomerCommand or a SaveCustomerCommand?

The answer is to tell Autofac about it!

In order to do so, we write a class the derives from Autofac.Module and override its Load method.
The Load method takes a single argument of type ContainerBuilder, which is all we need to
register new types.

http://www.ideliverable.com/blog/autofac­module 1/10
4/10/2015 IDeliverable ­ Autofac.Module

Let's see an example.

First, let's define an ICommand interface and two implementing classes:


SaveCustomerCommand and CreateOrderCommand:

Commands/ICommand.cs:

public interface ICommand {
        void Execute();
    }

Commands/SaveCustomerCommand.cs:

public class SaveCustomerCommand : ICommand {
        private readonly ICommerceServices _services;
 
        // Commands support DI just like any other class
        public SaveCustomerCommand(ICommerceServices services) {
            _services = services;
        }
 
        public void Execute() {
            // perform some action here, e.g. create a new customer or update an existing o
ne
        }
    }

Commands/CreateOrderCommand.cs:

http://www.ideliverable.com/blog/autofac­module 2/10
4/10/2015 IDeliverable ­ Autofac.Module

public class CreateOrderCommand : ICommand
    {
        private readonly ICommerceServices _services;
 
        // Commands support DI just like any other class
        public CreateOrderCommand(ICommerceServices services)
        {
            _services = services;
        }
 
        public void Execute()
        {
            // perform some action here, e.g. create a new order
        }
    }

The ICommerceService interface is just a sample interface without any members:

Services/ICommerceServices.cs:

public interface ICommerceServices {}

Next, we'll define two controllers where one controller takes a dependency on
SaveCustomerCommand while the other takes a dependency on CreateOrderCommand.

Controllers/CustomerController.cs:

http://www.ideliverable.com/blog/autofac­module 3/10
4/10/2015 IDeliverable ­ Autofac.Module

public class CustomerController : Controller {
        private readonly SaveCustomerCommand _saveCommand;
 
        // Inject a SaveCustomerCommand
        public CustomerController(SaveCustomerCommand saveCommand) {
            _saveCommand = saveCommand;
        }
 
        public ActionResult CreateCustomer() {
            _saveCommand.Execute();
            return Content("Customer created");
        }
    }

Controllers/OrderController.cs:

using System.Web.Mvc;
using Orchard.Docs.Misc.Commands;
 
namespace Orchard.Docs.Misc.Controllers {
    public class OrderController : Controller {
        private readonly CreateOrderCommand _createOrderCommand;
 
        // Inject a CreateOrderCommand
        public OrderController(CreateOrderCommand createOrderCommand) {
            _createOrderCommand = createOrderCommand;
        }
 
        public ActionResult CreateOrder() {
            _createOrderCommand.Execute();
            return Content("Order created");
        }
    }
}

Now, in order to allow this to work, we need to tell Autofac how to give us these command types.
Create another class that derives from Autofac.Module (note that you need to add a reference to
the Autofac assembly, which is located in the "Lib" folder that comes with Orchard's source).

ModuleBuilders/CommandsModule.cs:

http://www.ideliverable.com/blog/autofac­module 4/10
4/10/2015 IDeliverable ­ Autofac.Module

using Autofac;
using Autofac.Features.ResolveAnything;
 
public class CommandsModule : Module {
    protected override void Load(ContainerBuilder builder)
    {
        // Configure Autofac to create a new instance of any type that implements ICommand 
when such type is requested
        builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource(t => t.IsAssig
nableTo<ICommand>()));
    }
}

Basically, we're registering a new RegisterSource of type


AnyConcreteTypeNotAlreadyRegisteredSource, passing in a predicate of which types to
register. We're telling it to register all types that implement ICommand by taking advantage of
the IsAssignableTo<T> extension method that comes with Autofac.

The effect: whenever we request a type that implements ICommand, Autofac will provide in
instance of that type for us.

 11/10/2014 03:47 AM by Sipke Schoorstra (/blog/author/sipke)

7 comments
Ronald-rademaker 04/23/2012 03:03 PM

Nice ook #orchardcms zelf sta je lekker bezig

Sipke Schoorstra 04/23/2012 03:05 PM [http://www.ideliverable.com]


(http://www.ideliverable.com)

Je bedoelt dat je ook met Orchard bezig bent?

http://www.ideliverable.com/blog/autofac­module 5/10
4/10/2015 IDeliverable ­ Autofac.Module

Mobile Apps Development 04/27/2012 06:59 AM


[http://mindinventory.com/mobile_apps_dev.php]
(http://mindinventory.com/mobile_apps_dev.php)

Really,it's very useful code.

Leslie Fang 11/28/2012 03:25 PM

now that you want to inject an concrete class , there is no need to use Ioc , we
can instantiate it directly.

Leslie Fang 11/28/2012 03:33 PM

I also want to know if we have two classes derived from the same interface,
then when we inject that interface, how can orchard knows to call which
class. I write a demo Orchard will inject only one class, it seems the later class
override the pre class. I want to know how Orchard do that? Thanks!

Leslie Fang 11/28/2012 03:33 PM

I also want to know if we have two classes derived from the same interface,
then when we inject that interface, how can orchard knows to call which
class. I write a demo Orchard will inject only one class, it seems the later class
override the pre class. I want to know how Orchard do that? Thanks!

http://www.ideliverable.com/blog/autofac­module 6/10
4/10/2015 IDeliverable ­ Autofac.Module

Jake Bruun 01/30/2013 03:03 AM

Thanks for the great post Sipke! I've done similar thing with other ioc
containers, but it's nice to see the Autofac flavor and how to works with
Orchard.

Leave a comment
Name:

Enter your name

Email address:

Enter your email address

Not displayed on the site, used to obtain Gravatar image.

URL:

Enter your website URL

Comment:

How to Format

Type the text
Privacy & Terms
(http://www.google.com/intl/en/policies/)

http://www.ideliverable.com/blog/autofac­module 7/10
4/10/2015 IDeliverable ­ Autofac.Module

Submit

 Subscribe to IDeliverable Blog (RSS)


(/rss?containerid=32)

 Subscribe (email) (/subscribe)

Topics
autofac (1) (/Tags/autofac) azure (2) (/Tags/azure) cloud services (2) (/Tags/cloud%20services)

codemirror (1) (/Tags/codemirror) globalization (1) (/Tags/globalization) jquery (1) (/Tags/jquery)

knockoutjs (1) (/Tags/knockoutjs) linqjs (1) (/Tags/linqjs) orchard (33) (/Tags/orchard)

orchard harvest (1) (/Tags/orchard%20harvest) performance (2) (/Tags/performance)

powershell (2) (/Tags/powershell) ssl (1) (/Tags/ssl) startup tasks (2) (/Tags/startup%20tasks)

webapi (1) (/Tags/webapi)

Authors
Daniel Stolt (/blog/author/daniel)
Daniel is the go-to guy here at IDeliverable for all things Azure. He
blogs about his experiences developing for the cloud.

(/blog/author/daniel)

http://www.ideliverable.com/blog/autofac­module 8/10
4/10/2015 IDeliverable ­ Autofac.Module

Sipke Schoorstra (/blog/author/sipke)


Sipke is the resident Orchard CMS specialist here at IDeliverable. He
blogs about site building and module development.

(/blog/author/sipke)

Archive
2014 2013 2012
November (6) December (2) October (1)
(/blog/archive/2014/11) (/blog/archive/2013/12) (/blog/archive/2012/10)
September (3) June (5) September (3)
(/blog/archive/2014/9) (/blog/archive/2013/6) (/blog/archive/2012/9)
March (9) August (1)
(/blog/archive/2013/3) (/blog/archive/2012/8)
January (1) April (7)
(/blog/archive/2013/1) (/blog/archive/2012/4)
February (4)
(/blog/archive/2012/2)
January (18)
(/blog/archive/2012/1)

Postal address:
IDeliverable, Ltd.
PO Box 58341
3733 Limassol
CYPRUS

http://www.ideliverable.com/blog/autofac­module 9/10
4/10/2015 IDeliverable ­ Autofac.Module

Visiting address:
IDeliverable, Ltd.
Sotiri Tofini 4, 2nd floor
Agios Athanasios
4102 Limassol
CYPRUS

VAT number: CY10318155U


TIC number: 12318155W
info@ideliverable.com (mailto:info@ideliverable.com)
http://www.ideliverable.com (http://www.ideliverable.com)

All information on this website copyright © 2015 by IDeliverable, Ltd.

http://www.ideliverable.com/blog/autofac­module 10/10

You might also like