使用Model View Presenter(MVP)实现CastleWindsor

时间:2013-08-27 14:51:52

标签: c# castle-windsor mvp

我想用MVP模式实现CastleWindsor,但是当调用存储库来获取某些数据时,我不断在Presenter上获得“对象引用未设置为对象引用”。

我就是这样做的,我想知道是否有什么不对,所以如果可以,请告诉我:

主讲人:

public class CategoryPresenter
{
    ICategoryRepository categoryRepository;
    ICategoryView categoryView;

    public CategoryPresenter(ICategoryView _categoryView, ICategoryRepository _categoryRepository)
    {
        categoryView = _categoryView;
        categoryRepository = _categoryRepository;
    }

    //public CategoryPresenter(ICategoryView _categoryView) : this (_categoryView, new CategoryRepository())
    //{ }

    public CategoryPresenter(ICategoryView _view)
    {
        categoryView = _view;
    }

    public IEnumerable<object> GetActiveCategories()
    {
      return  categoryRepository.GetActiveCategories();
    }
}

IoC类:

public  static class IoC
{
    public static IWindsorContainer windsorContainter { get; set; }
}

IoCConfig类:

类IoCConfig     {

    public static IWindsorContainer RegisterCastleWindsorContainer()
    {
        IWindsorContainer windsorContainer = new WindsorContainer()
        .Install(new RepositoryInstaller())

        IoC.windsorContainter = windsorContainer;

        return windsorContainer;
    }

}

安装程序类:

public class RepositoryInstaller: IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<ICategoryRepository>().ImplementedBy<CategoryRepository>).LifestyleTransient());

    }
}

最后在Global.ascx文件中我在App_Start执行此操作:

    void Application_Start(object sender, EventArgs e)
    {            
        // Code that runs on application startup
        IoCConfig.RegisterCastleWindsorContainer();
    }

这样,错误信息如上所述;错误发生在演示者的方法:GetActiveCategories();

正如你在代码中看到的那样,我在容器上调用resolve方法。

如果您有任何建议,请告诉我。

谢谢。

1 个答案:

答案 0 :(得分:0)

我已将此解析为 IoC Class

    public static T Resolve<T>()
    {
        try
        {
            return windsorContainer.Resolve<T>();
        }
        catch (Exception e)
        {
            throw e;
        }
    }

然后将其添加到演示者:

   ICategoryRepository categoryRepository = IoC.Resolve<ICategoryRepository>();
   ICategoryView categoryView = IoC.Resolve<ICategoryView>();