我們公司正在使用Ninject for DI。我必須用MVVM創建一個WPF應用程序,並且想要使用Catel。 因爲我們的服務具有DB DataContext注入Ninject,我不知道從哪裏開始。Catel與Ninject
我已經開始了一個準備好的骨架項目。 這是App.xaml.cs包含:
public partial class App : Application
{
public IKernel Container;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ConfigureContainer();
ComposeObjects();
Current.MainWindow.Show();
}
private void ConfigureContainer()
{
var modules = new INinjectModule[]
{
new ServiceModule()
};
Container = new StandardKernel(modules);
}
private void ComposeObjects()
{
Current.MainWindow = Container.Get<MainWindow>();
Current.MainWindow.Title = "DI with Ninject";
}
}
的ServiceModule
從NinjectModule
繼承。
與該代碼我可以使用此構造我MainWindow
:
public MainWindow(IAuthenticationService authenticationService)
{
InitializeComponent();
ViewModel = new MainWindowViewModel(authenticationService);
DataContext = ViewModel;
}
的IAuthenticationService
經App.xaml.cs和Ninject注入。在我看來,這個解決方案很難維護,因爲如果我需要一個新服務,我必須將其添加到我的MainWindow
的構造函數中。 現在我需要與Catel一樣的工作,但是我沒有在文檔中找到任何東西。
編輯: 我在文檔中發現我可以註冊一個外部IoC容器。 如何創建我自己的組件(文檔:替換默認組件),它與Ninject的標準內核一起使用?
此外,這是DI的一個好方法還是有更好的解決方案?
你的意思是這種方法(NinjectDependencyResolver)? http://stackoverflow.com/questions/22221314/catel-ninject-ninject-activationexception-when-resolving-iuivisualizerservice 如果不是,我該如何讓Ninject內核實現接口? – 2014-11-06 11:07:57
不,即將到來的4.0已經改進了對外部容器的支持。您可以註冊容器(比如Ninject ServiceLocator),並且所有服務都應該自動爲您註冊。 – 2014-11-06 13:31:26