Sharepoint 2010中的依赖注入

8
我正在开展我的第一个SharePoint项目。是否有办法在SharePoint中使用依赖注入(如Castle Windsor)?如果可以,请提供一个示例代码。
谢谢。
2个回答

0
你可以像下面这样做。但这并不太好,因为SharepointClass是由Sharepoint实例化而不是由依赖注入容器实例化的。所以现在,在SharepointClass中,你可以通过Ioc.Resolve()来解决你的依赖关系,并且IService实例的更深层次的依赖项将由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>();
    }
}

而在你的SharePoint类中

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

3
虽然依赖注入和服务定位器都试图解决同一个问题,但我认为服务定位器是有风险的。请参考http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx了解详细信息。 - Malte Clasen
3
ServiceLocation和DependencyInjection(DI)不是一回事。DI意味着注入一个依赖项,而ServiceLocation是获取一个依赖项的调用。如果我说错了,请纠正我。 - Rookian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接