将 mvc-mini-profiler 与 EF 4.0 和 Ninject 结合使用

2024-04-22

我正在尝试将新的 mvc-mini-profiler 与基于 EF4 的应用程序一起使用,但我不知道如何正确连接到目标数据源。

据我所知。

Func<IMyContainer> createContainer = () =>
{
    var profiler = MiniProfiler.Current;

    if (profiler != null)
    {
        var rootConn = // ????
        var conn = ProfiledDbConnection.Get(rootConn);
        return ObjectContextUtils.CreateObjectContext<MyContainer>(conn);
    }
    else
    {
        return new MyContainer();
    }
};

kernel.Bind<IMyContainer>().ToMethod(ctx => createContainer()).InRequestScope();

如何在没有容器本身的情况下获得与 EF 容器的连接?我只是新建一个 SqlConnection,只不过连接字符串包含在所有 EF 垃圾中。


稍微不那么hacky的方式:

private static SqlConnection GetConnection()
{
    var connStr = ConfigurationManager.ConnectionStrings["ModelContainer"].ConnectionString;
    var entityConnStr = new EntityConnectionStringBuilder(connStr);
    return new SqlConnection(entityConnStr.ProviderConnectionString);
}

Amendment by John Gietzen:

所有答案的组合应该适用于实体框架支持的任何后备存储。

public static DbConnection GetStoreConnection<T>() where T : System.Data.Objects.ObjectContext
{
    return GetStoreConnection("name=" + typeof(T).Name);
}

public static DbConnection GetStoreConnection(string entityConnectionString)
{
    // Build the initial connection string.
    var builder = new EntityConnectionStringBuilder(entityConnectionString);

    // If the initial connection string refers to an entry in the configuration, load that as the builder.
    object configName;
    if (builder.TryGetValue("name", out configName))
    {
        var configEntry = WebConfigurationManager.ConnectionStrings[configName.ToString()];
        builder = new EntityConnectionStringBuilder(configEntry.ConnectionString);
    }

    // Find the proper factory for the underlying connection.
    var factory = DbProviderFactories.GetFactory(builder.Provider);

    // Build the new connection.
    DbConnection tempConnection = null;
    try
    {
        tempConnection = factory.CreateConnection();
        tempConnection.ConnectionString = builder.ProviderConnectionString;

        var connection = tempConnection;
        tempConnection = null;
        return connection;
    }
    finally
    {
        // If creating of the connection failed, dispose the connection.
        if (tempConnection != null)
        {
            tempConnection.Dispose();
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 mvc-mini-profiler 与 EF 4.0 和 Ninject 结合使用 的相关文章

随机推荐