简体   繁体   English

如何使用 caliburn micro 在 Wpf 中注入 EF DbContext

[英]How to Inject EF DbContext in Wpf using caliburn micro

I try to build WPF application to interact with database through Repositories above Entity framework, and I use caliburn micro as MVVM framework我尝试构建 WPF 应用程序通过 Entity 框架之上的 Repositories 与数据库交互,我使用caliburn micro作为 MVVM 框架

the problem is when I try to inject Repertories in ViewModels Through Simple Container it does not instantiate My DbContext问题是当我尝试通过简单容器在 ViewModels 中注入 Repertories 时,它不会实例化 My DbContext

Repository存储库

public class UserRepo : IUserRepo
{
    private AppDb _ctx;

    public UserRepo(AppDb ctx)
    {
            _ctx = ctx;
    }
}

application context应用上下文

public class AppDb : DbContext
{
    public AppDb(DbContextOptions options) : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
}

configuration on Simple Container简单容器上的配置

class Bootstrapper : BootstrapperBase
{

    private SimpleContainer _container = new SimpleContainer();
    private AppDb _db;
    public Bootstrapper()
    {
        Initialize();

        var options = new DbContextOptionsBuilder<AppDb>()
                      .UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=XRaySystem;Integrated Security=True;")
                      .Options;

        _db = new AppDb(options);
    }

    protected override void Configure()
    {
        _container.Instance(_container);

        _container
            .Singleton<IWindowManager, WindowManager>()
            .Singleton<IEventAggregator, EventAggregator>();
        //register the DataContext
        // i don't know how to add it
        _container.RegisterInstance(typeof(AppDb), null, _db); // <<<<<<<<<< how to add this correctly 
        //Register Reporisotries
        _container
            .PerRequest<IUserRepo, UserRepo>();
        //Register ViewModels
        GetType().Assembly.GetTypes()
            .Where(type => type.IsClass)
            .Where(type => type.Name.EndsWith("ViewModel"))
            .ToList()
            .ForEach(viewModelType => _container.RegisterPerRequest(
                viewModelType, viewModelType.ToString(), viewModelType));
    }
    protected override void OnStartup(object sender, StartupEventArgs e)
    {


        DisplayRootViewFor<DashBoardViewModel>();
        //base.OnStartup(sender, e);
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }


    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}

View model查看 model

class DoctorViewModel : Screen
{
    private readonly IUserRepo _userRepo;

    public DoctorViewModel(IUserRepo userRepo)
    {
        _userRepo = userRepo;
    }
}

UserRepo is instantiated but with null AppDb UserRepo已实例化,但使用 null AppDb

my Question我的问题

How to configure Simple Container to Add AppDb to UserRepo ?如何配置 Simple Container 以将AppDb添加到UserRepo

I have reproduced the same problem in on GitHub在 GitHub 上重现了同样的问题

After some debugging, I found that Configure Method run first then the constructor call !!经过一番调试,我发现先运行Configure方法,然后调用构造函数! So the instantiation is happened after the Configuration already done with null所以实例化是在 null 完成配置之后发生的

I solve it by adding the instantiation of _db in Configure method itself我通过在Configure方法本身中添加 _db 的实例化来解决它

class Bootstrapper : BootstrapperBase
{

    private SimpleContainer _container = new SimpleContainer();
    private AppDb _db;
    public Bootstrapper()
    {
        Initialize();
    }

    protected override void Configure()
    {
        var options = new DbContextOptionsBuilder<AppDb>()
                     .UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=XRaySystem;Integrated Security=True;")
                     .Options;

        _db = new AppDb(options); //<<<< solve the problem

        _container.Instance(_container);

        _container
            .Singleton<IWindowManager, WindowManager>()
            .Singleton<IEventAggregator, EventAggregator>();
        //register the DataContext
        _container.Instance(_db);
        // _container.RegisterInstance(typeof(AppDb), null, _db); 
        
         //Register Reporisotries
         _container
            .PerRequest<IUserRepo, UserRepo>();
        //Register ViewModels
        GetType().Assembly.GetTypes()
            .Where(type => type.IsClass)
            .Where(type => type.Name.EndsWith("ViewModel"))
            .ToList()
            .ForEach(viewModelType => _container.RegisterPerRequest(
                viewModelType, viewModelType.ToString(), viewModelType));
    }
    protected override void OnStartup(object sender, StartupEventArgs e)
    {

        DisplayRootViewFor<DashBoardViewModel>();
        //base.OnStartup(sender, e);
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }


    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Caliburn.Micro MVVM 正确设置 WPF 文本框的样式? - How to properly style a WPF TextBox using Caliburn.Micro MVVM? 如何使用caliburn.micro WPF抓取webbrowser.document - How to grab webbrowser.document using caliburn.micro WPF 在WPF中,应用程序MainWindow为空(使用Caliburn Micro) - Application MainWindow is null in WPF (using Caliburn Micro) 如何将WPF NotifyIcon与Caliburn.Micro集成 - How to integrate WPF NotifyIcon with Caliburn.Micro 使用 Caliburn Micro 将 EventAggregator 注入 ViewModel - Inject EventAggregator into ViewModel with Caliburn Micro 如何在Caliburn.Micro中将依赖项注入视图模型? - How to inject dependencies into view models in Caliburn.Micro? C# WPF 使用 Caliburn.Micro:如何将 IEnumerable 转换为 BindableCollection? - C# WPF using Caliburn.Micro: How can I convert an IEnumerable to BindableCollection? C#:Caliburn Micro:如何使用数据绑定控制 WPF 按钮的属性? - C#: Caliburn Micro: How do I control the properties of a WPF Button using data binding? 当我使用caliburn micro时,如何将wpf网格上的按钮绑定到MVVM上的方法 - How to bind a button on wpf grid to a method on MVVM when I am using caliburn micro 如何使用Caliburn.Micro MVVM在WPF中的同一视图上从另一个视图模型更新list &lt;&gt;? - How to update list<> from another View model on same View in WPF using Caliburn.Micro MVVM?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM