Asp.net mvc Asp核心,对象引用未设置为存储库模式中对象的实例

Asp.net mvc Asp核心,对象引用未设置为存储库模式中对象的实例,asp.net-mvc,asp.net-core,repository,repository-pattern,Asp.net Mvc,Asp.net Core,Repository,Repository Pattern,我正在开发asp core 1.1,我想在我的项目中创建一个selectrepository模式 存储库类中的我的代码: public class AuthorReposetory : IDisposable { private static ApplicationDbContext _context; public AuthorReposetory(ApplicationDbContext context) { _context = context;

我正在开发asp core 1.1,我想在我的项目中创建一个
select
repository模式

存储库类中的我的代码:

public class AuthorReposetory : IDisposable
{
    private static ApplicationDbContext _context;

    public AuthorReposetory(ApplicationDbContext context)
    {
        _context = context;
    }




    public static List<Author> GetAuthorList()
    {
        List<Author> model = new List<Author>();

        model = _context.authors.Select(a => new Author
        {
            AuthorId = a.AuthorId,
            AuthorName = a.AuthorName,
            AuthorDescription = a.AuthorDescription
        }).ToList();

        return model;
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    ~AuthorReposetory()
    {
        Dispose();
    }
}
更新

这是我的创业课程

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //define Connection string
        services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefualtConnection")));
        //For Create and use identity in database
        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();


        // Add framework services.
        services.AddMvc();
        services.AddAutoMapper();
        services.AddPaging();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseIdentity();


        app.UseMvc(routes =>
        {

            //New Area For Admin
            routes.MapRoute(
                name: "Admin",
                template: "{area:exists}/{controller=Admin}/{action=Index}/{id?}");

            //New Area For User
            routes.MapRoute(
                name: "UserProfile",
                template: "{area:exists}/{controller=UserProfile}/{action=Index}/{id?}");

            //tranditional Routing
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
问题是运行
model=\u context.authors.Select(a=>newauthor
时,
对象引用未设置为对象的实例。
在上面的代码中,我展示了控制器代码、存储库类代码和启动代码。
问题出在哪里


注意:controller中的一切都很好。问题在于repository类。

可能您的_上下文对象为空。您的DI/IoC是如何配置的?我将以这种方式进行调查

应按如下方式添加数据库上下文:

public void配置服务(IServiceCollection服务) { services.AddDbContext(options=>options.UseSqlite(“数据源=blog.db”); }


以下是有关如何配置数据库上下文的文档:

您尚未在
服务中注册存储库类,因此无法通过容器解决该问题。请在
配置服务
方法中尝试以下操作:

services.AddScoped<AuthorReposetory>();
services.addScope();

您使用的是静态方法,由于您从未创建对象,因此从未调用构造函数。您必须将构造函数更改为:

public static AuthorReposetory()
{
    _context = new ApplicationDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefualtConnection")));
}
但这是一种非常糟糕的做法,因为您必须在构造函数中设置连接,这也创建了对上下文类的硬依赖

更好的解决方案是创建一个非静态类

public class AuthorRepository : IAuthorRepository
{
    private ApplicationDbContext _context;

    public AuthorRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    // ...
}

public interface IAuthorRepository
{
    // ...
}
使用注入反转依赖关系:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    //define Connection string and setup dependency injection
    services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefualtConnection")));
    services.AddScoped<IAuthorRepository, AuthorRepository>();
    // ...
}

@hix my context在没有存储库和控制器的情况下工作,但当我在存储库类中使用它时,有什么办法解决它吗?好的,我在您的配置中看不到任何控制器或存储库。包括它们,您的解决方案将工作;)我认为当您从控制器调用AuthorReposetory类时会发生异常。请不要在dispose方法中放置异常。这就像是你朝自己的脑袋开了一枪:)我不知道我到底要做什么?你必须把你的回购协议和服务类添加到依赖注入中。您可以在startup类中的ConfigureServices方法中执行此操作。语法如下:services.AddTransient(TMyInterfaceImplementation);显示您配置的启动类context@EhsanSajjad我将其添加到问题中可能是连接字符串不正确,正如您在startup@EhsanSajjad我需要放置连接的代码吗?为什么您的
\u上下文在
AuthorRepository
中是静态的?我将其添加到
configureservices
中,但存储库构造函数不再工作我认为这应该可以工作,可能您还缺少其他内容,可能我需要在controller中创建一个新的存储库实例来使用它
服务。AddDbContext()
在DI中注册DbContext。没有必要再这样做了。最好是按作用域添加存储库,而不是临时添加。编辑。
public class AuthorRepository : IAuthorRepository
{
    private ApplicationDbContext _context;

    public AuthorRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    // ...
}

public interface IAuthorRepository
{
    // ...
}
public void ConfigureServices(IServiceCollection services)
{
    //define Connection string and setup dependency injection
    services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefualtConnection")));
    services.AddScoped<IAuthorRepository, AuthorRepository>();
    // ...
}
public HomeController
{
    private IAuthorRepository _authorRepository;

    public HomeController(IAuthorRepository authorRepository)
    {
        _authorRepository = authorRepository;
    }

    [HttpGet]
    public IActionResult Index()
    {
        var q = _autorRepository.GetAuthorList();
        return View(q);
    }
}