我正在用AspNetCore1.1制作一个RESTfull API,这是我第一次使用net,我变得相当困惑。
我需要从我的应用程序中访问一个neo4j数据库,但是我只需要设置一次到数据库的连接,这样我就不必对每个请求重新连接到数据库。因此,我已经创建了一个类,它将处理建立连接的问题,然后有一个newSession()方法,它将非常明显地返回一个新的ISession实例,我可以用该实例查询数据库。
这是我目前拥有的代码:
namespace DependencyInjection.Interfaces
{
public interface IDatabaseSessionRepository
{
IDriver Driver { get; set; }
void IDatabaseSessionRepository();
ISession newSession();
}
public interface IDatabaseRepository
{
ISession Session { get; set; }
void IDatabaseRepository();
}
}和
namespace DependencyInjection.Methods
{
public class DatabaseSessionRepository : IDatabaseSessionRepository
{
public IDriver Driver { get; set; }
public void IDatabaseSessionRepository()
{
Driver = GraphDatabase.Driver("bolt://localhost:8797", AuthTokens.Basic("neo4j", "neo4j"));
}
public ISession newSession()
{
return Driver.Session();
}
}
public class DatabaseRepository : IDatabaseRepository
{
public ISession Session { get; set; }
public void IDatabaseRepository()
{
//I want to access an instance of the DatabaseSessionRepository class
//here
}
//other methods here
}
}我希望有一个DatabaseSessionRepository实例,并且能够在DatabaseRepository类中访问它,这样我就可以获得ISession实例。
我想的是我可以在DatabaseSessionRepository上使用DatabaseSessionRepository(),但是如何在DatabaseRepository类中实例化它一次并能够访问呢?
我还将使用services.AddScoped<>()生命周期来处理DatabaseRepository,就像您知道的那样。
发布于 2017-05-27 12:22:02
那不是更容易吗?
services.AddSingleton<IDriver>(p => GraphDatabase.Driver("bolt://localhost:8797", AuthTokens.Basic("neo4j", "neo4j"));
services.AddScoped<ISession>(p => p.GetService<IDriver>().Session());这确保在整个应用程序生存期内只创建一个IDriver实例,并且每次请求ISession时,它都被解析为一个作用域服务(整个请求的单个ISession ),然后再进行处理。
然后,您可以在任何控制器中注入ISession:
public class MyController : Controller
{
private readonly ISession _session;
public MyController(ISession session)
{
_session = session;
}
}当然,在DI容器内注册的任何其他类中:
// inside ConfigureServices:
services.AddScoped<IDatabaseRepository, DatabaseRepository>();
// your class:
public class DatabaseRepository : IDatabaseRepository
{
public ISession Session { get; set; }
public DatabaseRepository(ISession session)
{
Session = session;
}
//other methods here
}https://stackoverflow.com/questions/44216507
复制相似问题