开发者

Dependency Injection in Sharepoint 2010

I'm w开发者_Python百科orking 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


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


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜