我可以在ViewModel中为DbContext使用依赖注入吗? Core2.0

时间:2017-08-19 19:51:21

标签: c# mvvm dependency-injection asp.net-core asp.net-core-2.0

我正在尝试从框架项目将应用程序迁移到Core 2.0。我遇到的问题与this one非常相似,但我正在尝试使用DI。我根据该问题创建了一个示例项目,但使用的视图模型类似于我在项目中使用它的方式。我一直想弄清楚我一天之内做错了什么,所以希望这里有人可以提供帮助。

In case It's helpful code on github

在做了一些研究后,我根据本文中的评论改变了我的应用程序使用视图模型的方式,并开始使用Repository Pattern。我更新了git hub示例以反映我的更改,以防它可以帮助任何人。

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

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

我错误地说new GigsViewModel();因为我需要将选项传递给ApplicationDbContext

  

没有任何论据符合所要求的形式   参数&#39;选项&#39;的   &#39; ApplicationDbContext.ApplicationDbContext(DbContextOptions)&#39;

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

    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();
    }

1 个答案:

答案 0 :(得分:1)

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

这样的事情应该有效:

private readonly GigsViewModel _gigsViewModel;

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

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