使用 PetaPoco 与 StructureMap 的共享连接

发布于 2024-12-05 06:13:47 字数 1703 浏览 7 评论 0原文

这是我当前在 Global.asax 中实现的 StructureMap:

var container = (IContainer)IOCContainer.Initialize();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));

下面是上面提到的代码:

public static class IOCContainer
    {
        public static IContainer Initialize()
        {
            ObjectFactory.Initialize(x =>
            {
                x.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.AddAllTypesOf<IController>();
                });

                x.For<IConfigRepository>().Use<ConfigRepository>();
            });
            return ObjectFactory.Container;
        }

    }

public class StructureMapDependencyResolver : IDependencyResolver
    {
        public StructureMapDependencyResolver(IContainer container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType.IsAbstract || serviceType.IsInterface)
            {
                return _container.TryGetInstance(serviceType);
            }
            else
            {
                return _container.GetInstance(serviceType);
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAllInstances<object>()
                .Where(s => s.GetType() == serviceType);
        }

        private readonly IContainer _container;
    }

我读到使用共享连接可能会稍微提高性能,所以我想知道如何在我的 MVC 应用程序中使用它。我想我必须将新创建的 PetaPoco.Database 对象传递给我的存储库的构造函数?

谢谢

This is my current implementation of StructureMap in Global.asax:

var container = (IContainer)IOCContainer.Initialize();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));

Below is the code that is refered to above:

public static class IOCContainer
    {
        public static IContainer Initialize()
        {
            ObjectFactory.Initialize(x =>
            {
                x.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.AddAllTypesOf<IController>();
                });

                x.For<IConfigRepository>().Use<ConfigRepository>();
            });
            return ObjectFactory.Container;
        }

    }

public class StructureMapDependencyResolver : IDependencyResolver
    {
        public StructureMapDependencyResolver(IContainer container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType.IsAbstract || serviceType.IsInterface)
            {
                return _container.TryGetInstance(serviceType);
            }
            else
            {
                return _container.GetInstance(serviceType);
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAllInstances<object>()
                .Where(s => s.GetType() == serviceType);
        }

        private readonly IContainer _container;
    }

I have read that using the shared connection may improve performance a little bit so I was wondering how to use this in my MVC app. I guess I would have to pass a newly created PetaPoco.Database object to the constructors of my repositories??

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦毁影碎の 2024-12-12 06:13:47

我只能代表 Autofac,因为这是我在项目中使用的。这可能不适用于您想要做的事情,但我不妨分享一下。为了根据http请求获取petapoco数据库对象,我在global.asax.cs中有这个配置,

builder.RegisterType<MyProject.ObjectRelationalMapper.PetaPoco.Database>()
                .As<MyProject.ObjectRelationalMapper.PetaPoco.Database>()
                .WithParameters( new List<NamedParameter>() {new NamedParameter( "connectionStringName", "MyProjectConnectionString")})
                .InstancePerHttpRequest();

MyProject.ObjectRelationalMapper.PetaPoco只是我重命名的petapoco.cs。

在 Autofac 中,您可以通过 WithParameters() 告诉它要传入哪些参数,从而告诉它要调用哪个版本的构造函数。构造对象时,它会找到具有匹配参数的构造函数。

每次构造函数注入其依赖项时,它都会在整个 http 请求中使用相同的 petapoco 数据库对象,因为这就是我告诉 Autofac 要做的事情 (InstancePerHttpRequest)

我的控制器构造函数采用 INextMatchService 作为依赖项,而后者又采用 INextMatchRepository 作为依赖项:

public NextMatchRepository( Database database, ISessionWrapper sessionWrapper)
{
    this._database = database;
    this._sessionWrapper = sessionWrapper;
}

“Database”类型是MyProject.ObjectRelationalMapper.PetaPoco.Database,它是在上面的代码片段中构造的。现在我的存储库可以使用共享数据库连接。当您使用 Petapoco 函数时,它会检查是否已存在要使用的连接,如果存在,则会增加计数器并使用该对象:

// Open a connection (can be nested)
public void OpenSharedConnection()
{
    if (_sharedConnectionDepth == 0)
    {
        _sharedConnection = _factory.CreateConnection();
        _sharedConnection.ConnectionString = _connectionString;
        _sharedConnection.Open();

        if (KeepConnectionAlive)
            _sharedConnectionDepth++;// Make sure you call Dispose
    }
    _sharedConnectionDepth++;
}

I can only speak for Autofac as that's what I use in my project. This might not apply to what you're trying to do but I might as well share it. To get a petapoco database object per http request I have this config in global.asax.cs

builder.RegisterType<MyProject.ObjectRelationalMapper.PetaPoco.Database>()
                .As<MyProject.ObjectRelationalMapper.PetaPoco.Database>()
                .WithParameters( new List<NamedParameter>() {new NamedParameter( "connectionStringName", "MyProjectConnectionString")})
                .InstancePerHttpRequest();

MyProject.ObjectRelationalMapper.PetaPoco is just my renameapaced petapoco.cs.

In Autofac you can tell it which version of the constructor to call by telling it which parameters you are passing in via WithParameters(). When constructing your object it finds the constructor with matching parameters.

Every time a constructor has its dependencies injected it uses the same petapoco database object throughout the http request, because that's what I told Autofac to do (InstancePerHttpRequest)

My controller constructor takes an INextMatchService as a dependency which in turn takes an INextMatchRepository as a dependency :

public NextMatchRepository( Database database, ISessionWrapper sessionWrapper)
{
    this._database = database;
    this._sessionWrapper = sessionWrapper;
}

The "Database" type is MyProject.ObjectRelationalMapper.PetaPoco.Database, which is constructed in the above code snippet. Now my repository can work with a shared database connection. As you work with the Petapoco functions it checks if there is already a connection to use, if there is it increments the counter and uses the object :

// Open a connection (can be nested)
public void OpenSharedConnection()
{
    if (_sharedConnectionDepth == 0)
    {
        _sharedConnection = _factory.CreateConnection();
        _sharedConnection.ConnectionString = _connectionString;
        _sharedConnection.Open();

        if (KeepConnectionAlive)
            _sharedConnectionDepth++;// Make sure you call Dispose
    }
    _sharedConnectionDepth++;
}
疯到世界奔溃 2024-12-12 06:13:47

如果有人想知道的话我就这么做了:

x.For<PetaPoco.Database>().Singleton().Use(() => new PetaPoco.Database("DBConnection"));

I went with this if anyone wants to know:

x.For<PetaPoco.Database>().Singleton().Use(() => new PetaPoco.Database("DBConnection"));
迷途知返 2024-12-12 06:13:47

当您运行 PetaPoco 获得的 T4 时,您将获得以下可用信息。

{yourmodel}.ConnectionStringDB.GetInstance();

我会查找一个实例,如果有,则使用它,如果没有,则创建另一个实例。

不过我可能是错的……我不记得了。

When you run the T4 that you get with PetaPoco you will get the following available..

{yourmodel}.ConnectionStringDB.GetInstance();

I this looks for an instace, if there is one then it uses it if not it creates another.

I could be wrong on that though.. I cant fully remember.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文