Skip to content

Dependency Injection

nmosafi edited this page Feb 12, 2012 · 6 revisions

Whenever you write a handler, write a pipeline contributor, a URI decorator or any other object which you register with OpenRasta and which OpenRasta creates for you, you can take advantage of OpenRasta’s built-in dependency injection.

What does this mean?

In simple terms, when you write any of the above objects as POCOs, you can add any registered interface or type and OpenRasta will ensure that you get an instance of what you asked for when it creates your handler, contributor, or URI decorator.

Why is this useful?

Let’s take a look at an example. When you’re writing a handler, you’re just writing a POCO. This POCO doesn’t have any access to things you might be used to working with in vanilla ASP.NET (like an HttpRequest, for example) – and actually, most of the time you won’t need this info. For example’s sake, though, let’s say you needed access to the query string just as it arrived through IIS. All we have to do is add an IRequest object to our constructor. In this example, we print to the debug console what the client’s accept header contained: -

using OpenRasta.Web;

namespace OpenRasta.Docs.Handlers
{
    public class HomeHandler
    {
        public HomeHandler(IRequest request)
        {
            Debug.WriteLine(request.Headers["Accept"]);
        }

        public object Get() { return new HomeResource(); }
    }
}

We can take as many or as few dependencies as we wish – just add more constructor parameters. OpenRasta will remember what our constructor looks like and make sure we always have what we asked for to hand.

What can I get access to?

There are a number of available dependencies with a variety of useful pieces of information you can use.

How about my own interfaces?

Absolutely! Just tell OpenRasta about them with the ResourceSpace.Uses.CustomDependency method. Suppose we want to get a concrete implementation of our own type IArticleRepository in an ArticleHandler we’ve written. First, we tell OpenRasta about the interface and what is implementing it, and what its lifetime is.

  ResourceSpace.Uses.CustomDependency<IArticleRepository, ArticleRepository>(DependencyLifetime.Singleton);

Then we just use the IArticleRepository directly in our ArticleHandler constructor:

  public class ArticleHandler
  {
      private readonly IArticleRepository articles;
      public ArticleHandler(IArticleRepository articles)
      {
          this.articles = articles;
      }

      public Articles Get()
      {
          return articles.GetAll();
      }
  }

If the type you’ve requested a dependency on is not registered, object creation will fail.

What about optional or “soft” dependencies?

Optional, or “soft” dependencies – that is, types you want to depend on but shouldn’t fail the object creation if they cannot be resolved – can be taken by property setter injection.

For example, let’s say you want to use an ILogger, but you don’t know if it’ll be available at runtime (perhaps your DI configuration has no logger, or you only configure the logger when tracking down problems in production). Your code could then look like the following:

public class ArticleHandler
{
    public ILogger Logger { get; set; }
    public ArticleHandler()
    {
        if (Logger != null)
            Logger.WriteDebug("Entering the article handler.");
    }
}

In this example, OpenRasta will inject the logger at ArticleHandler creation time if it is available, and if it’s not, will leave the property alone.

See Also

Next: Uri decorators

Something went wrong with that request. Please try again.