Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Dependency Injection with Sitecore
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="disublayout.ascx.cs" Inherits="Website.sublayouts.disublayout" %>
<%@ Register TagPrefix="sc" Namespace="Sitecore.Web.UI.WebControls" Assembly="Sitecore.Kernel" %>
<asp:Label runat="server" ID="demo" Text="initial text" />
using System;
using App.Abstract;
namespace Website.sublayouts
{
public partial class disublayout : System.Web.UI.UserControl
{
public IFooService SomeDependency { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
demo.Text = SomeDependency.GetData();
}
}
}
namespace App.Abstract
{
public interface IFooService
{
string GetData();
}
}
namespace App.Concrete
{
public class FooService : IFooService
{
public string GetData()
{
return "Modified at " + DateTime.Now.ToLongTimeString();
}
}
}
<%@Application Language='C#' Inherits="Website.Global" CodeBehind="Global.asax.cs" %>
using Autofac.Integration.Web;
using Sitecore.Web;
namespace Website
{
public class Global : Application, IContainerProviderAccessor
{
static IContainerProvider _containerProvider;
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
public void Application_Start()
{
_containerProvider = new ContainerProvider(ObjectBuilder.Register());
}
}
}
using Autofac;
using App.Abstract;
using App.Concrete;
namespace Website
{
public static class ObjectBuilder
{
public static IContainer Register()
{
var builder = new ContainerBuilder();
builder.Register<IFooService>(c => new FooService());
return builder.Build();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment