2011-03-07 19 views
8

我正在开发我的第一个共享点项目。有没有一种方法可以在sharepoint中使用依赖注入(如城堡windsor)? 如果可以,请提供samle代码。Sharepoint 2010中的依赖注入

感谢

+0

好问题;) – Rookian 2011-09-14 20:47:17

回答

0

从MS模式&实践组使用SharePoint服务定位器:http://spg.codeplex.com/

+3

虽然依赖注入和服务定位器尝试解决同样的问题,我认为服务定位危险。有关详细信息,请参阅http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx。 – 2011-06-15 08:49:31

+3

-1 ServiceLocation与DepdencyInjection(DI)不同。 DI意味着注入依赖关系,而服务位置则是获取依赖关系的呼叫。纠正我如果我错了。 – Rookian 2011-09-14 20:46:21

+3

绝对可怕!这不是依赖注射 – 2013-05-30 07:37:16

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