我可以在ViewModel中为DbContext使用依赖注入吗?核心2.0 [英] Can I use Dependency Injection in a ViewModel for DbContext? Core2.0

查看:54
本文介绍了我可以在ViewModel中为DbContext使用依赖注入吗?核心2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将应用程序从框架项目迁移到Core 2.0.我遇到的问题与这一个问题,但我正在尝试使用DI.我创建了一个符合该问题的示例项目,但使用的视图模型与我在项目中的用法类似.我一直在努力找出我一天来做错了什么,因此希望在座的人可以为您提供帮助.

I am trying to migrate an app to Core 2.0 from a framework project. The problem I am running into Is very Similar to this one, but I am trying to use DI. I created a sample project in line with that problem but using a view model similar to how I am using it in my project. I have been trying to figure out what I'm doing wrong to over a day so hopefully someone on here can help.

以防在github上有用的代码

进行了一些研究之后,我根据本文中的评论更改了应用程序使用视图模型的方式,并开始使用存储库模式.我更新了git hub示例以反映我的更改,以防它对任何人都有帮助.

After doing some Research, I changed the way my application was using my view model based on the comments in this post and started using the Repository Pattern. I updated the git hub example to reflect my changes in case it would help anyone.

ApplicationDbContext.cs

ApplicationDbContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Gig> Gigs { get; set; }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }

    public DbSet<gigs2.Models.Gig> Gig { get; set; }
}

GigsController.cs

GigsController.cs

public class GigsController : Controller
{
    // GET: Gigs
    public ActionResult Index()
    {
        GigsViewModel vm = new GigsViewModel();
        vm.Get();
        return View(vm);
    }
}

我在 new GigsViewModel();上报错了,它说是因为我需要将选项传递给ApplicationDbContext

I am erroring out on new GigsViewModel(); it says because I need to pass options to the ApplicationDbContext

没有给出与所需形式相对应的参数的参数选项"'ApplicationDbContext.ApplicationDbContext(DbContextOptions)'

There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions)'

GigsViewModels.cs

GigsViewModels.cs

 public class GigsViewModel
{
    private ApplicationDbContext _context;

    public GigsViewModel(ApplicationDbContext context) {
        _context = context;

    }
    public List<GigViewModel> Gigs { get; set; }

    public void Get()
    {
        Gigs = _context.Gigs.Select(g => new GigViewModel {
            Id = g.Id,
            Date = g.Date,
            Time = g.Time,
            Venue = g.Venue
        }).ToList();
    }
}

startup.cs

startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~.@ ";
            options.User.RequireUniqueEmail = false;
            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 4;
            options.Password.RequireDigit = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddScoped<UserManager<ApplicationUser>, ApplicationUserManager>();
        services.AddScoped<SignInManager<ApplicationUser>, ApplicationSignInManager<ApplicationUser>>();
        services.Configure<Configuration.cofAuthSettings>(Configuration.GetSection("cofAuthSettings"));


        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }

推荐答案

向您的 GigsController 类添加一个构造函数,该构造函数接受您的 GigsViewModel 的实例.这将允许IoC容器构造依赖关系树(而不是像您现在所做的那样自己创建它.

Add a constructor to your GigsController class which accepts an instance of your GigsViewModel. This will allow the IoC container to construct the dependency tree (instead of creating it yourself like you are doing at the moment.

类似的事情应该起作用:

Something like this should work:

private readonly GigsViewModel _gigsViewModel;

public GigsController(GigsViewModel gigsViewModel)
{
    _gigsViewModel = gigsViewModel;
}

// GET: Gigs
public ActionResult Index()
{
    _gigsViewModel.Get();
    return View(_gigsViewModel);
}

这篇关于我可以在ViewModel中为DbContext使用依赖注入吗?核心2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆