我正在开展我的第一个SharePoint项目。是否有办法在SharePoint中使用依赖注入(如Castle 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();
}
}
使用来自MS Patterns & Practices组的SharePoint服务定位器:http://spg.codeplex.com/