Dependency Injection in Sharepoint 2010
Asked Answered
R

2

8

I'm working on my first sharepoint project. Is there a way I can use dependency injection (like castle windsor) in sharepoint? If so can you please provide a samle code.

Thanks

Rutter answered 7/3, 2011 at 9:19 Comment(0)
C
0

Use the SharePoint Service Locator from the MS Patterns & Practices group: http://spg.codeplex.com/

Cathern answered 7/3, 2011 at 11:43 Comment(2)
While Dependency Injection and Service Locator try to solve the same problem, I consider Service Locator dangerous. See blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx for details.Julieannjulien
-1 ServiceLocation is not the same as DepdencyInjection (DI). DI means to inject a dependency meanwhile service location is a call for gaining a dependency. Correct me If I am wrong.Uphroe
B
0

You can do like below. But this is not awesome because, SharepointClass is instantiated by sharepoint not by the dependency injection container. So for now, in SharepointClass you can resolve your dependency like Ioc.Resolve() and deeper dependencies of IService instance will be injected by Windsor.

public interface IMyCode
{
    void Work();
}

public class MyCode : IMyCode
{
    public void Work()
    {
        Console.WriteLine("working");
    }
}

public interface IService
{
    void DoWork();
}

public class MyService : IService
{
    private readonly IMyCode _myCode;

    public MyService(IMyCode myCode)
    {
        _myCode = myCode;
    }

    public void DoWork()
    {
        Console.WriteLine(GetType().Name + " doing work.");
        _myCode.Work();
    }
}

public class Ioc
{
    private static readonly object Syncroot = new object();
    private readonly IWindsorContainer _container;
    private static Ioc _instance;

    private Ioc()
    {
        _container = new WindsorContainer();
        //register your dependencies here
        _container.Register(Component.For<IMyCode>().ImplementedBy<MyCode>());
        _container.Register(Component.For<IService>().ImplementedBy<MyService>());
    }

    public static Ioc Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (Syncroot)
                {
                    if (_instance == null)
                    {
                        _instance = new Ioc();
                    }
                }
            }
            return _instance;
        }
    }

    public static T Resolve<T>()
    {
        return Instance._container.Resolve<T>();
    }
}

And in your sharepoint class

public class SharepointClass : SharepointWebpart //instantiated by sharepoint
{
    public IService Service { get { return Ioc.Resolve<IService>(); } }

    public void Operation()
    {
        Console.WriteLine("this is " + GetType().Name);
        Service.DoWork();
    }
}
Bridgeboard answered 26/10, 2015 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.