2

We have services and repositories loaded by IoC.

/* registration in the service class for repository */
container.Register<IContainerRepository, ContainerRepository>();

/* registration in GUI app from service class and Form class for constructor injection usage */
container.Register<IContainerService, ContainerService>();
container.Register<rfrmContainerList, rfrmContainerList>();

So we have the ContainerRepository for data access and ContainerService for business logic.

ContainerRepository uses EF6 and Dapper (basically EF6 for simple queries and insert/update/delete methods while we use Dapper for running optimized queries against complex joined data). Every repository has the EF6 context passed by IoC in the class constructor. Dapper always get the ConnectionString from the context:

var testItem = Context.Container.FirstOrDefault();

using (SqlConnection connection = new SqlConnection(Context.Database.Connection.ConnectionString))
{
    var builder = new SqlBuilder();
...
    var items = connection.Query<ContainerDto>(sql.RawSql, sql.Parameters);
}

The ContainerService injected by constructor injection:

private readonly IContainerService _containerService;

public rfrmContainerList(IContainerService containerService)
{
    _containerService = containerService ?? throw new ArgumentNullException(nameof(containerService));
}

Now everything is set up, so I expect that if Dapper using the same ConnectionString as EF6 it will use the same authentication, right?

Nope. While var testItem = Context.Container.FirstOrDefault(); successfully returns the expected result Dapper fails at connection.Query<> throwing an exception says Login failed for user 'username' (username replaced to actual login name for my test user).

So after many tests and try I finally localized the main problem, it's something in the IoC.

/* This query will return successfully */

var localContainerService = IoC.Resolve<IContainerService>();
var container = localContainerService.ListContainers(new Model.QueryParams.DesktopApp.Operation.ContainerListQueryParams() { StatusDateFrom = new DateTime(2019, 8, 1), StatusDateTo = DateTime.Now.Date });

/* This query will fail with authentication */

var container2 = _containerService.ListContainers(new Model.QueryParams.DesktopApp.Operation.ContainerListQueryParams() { StatusDateFrom = new DateTime(2019, 8, 1), StatusDateTo = DateTime.Now.Date });

So the first query with locally resolved service object runs without any problem, takes the ConnectionString from the Context and connection.Query<ContainerDto>(sql.RawSql, sql.Parameters) returns an expected result.

The second query using the constructor injected service fails at the same line says "Login failed for user 'username'".

Strange but EF6 query var testItem = Context.Container.FirstOrDefault(); works for both cases.

Can anyone experience a similar problem? I've checked all my IoC registrations and can't figure out why this strange behavior happens.

1
  • Well, ContainerService and ContainerRepository are built for db table Container so it's not the same "container" object which represents Dryioc containers. Aug 29, 2019 at 15:04

3 Answers 3

4

There are multiple scenarios where that won't work. The good news is that you shouldn't be using two seperate SqlConnections in the first place. Just use the DbContext's SqlConnection for Dapper/ADO.NET. The DbContext will clean up the SqlConnection and you don't even need an additional using block.

So just something like:

class MyDb : DbContext
{

    public SqlConnection GetConnection()
    {
        var con = (SqlConnection)Database.Connection;
        if (con.State != System.Data.ConnectionState.Open)
        {
            con.Open();
        }
        return con;
    }

    // . . .
}
0
1

If you are using SQL Authentication (UId / Pwd) then EF does not reveal the password when you use context.Database.Connection.ConnectionString. For instance, output that to the Console and you get something like:

"Data Source=QH10373138\DEV2008R2;Initial Catalog=Spikes;uid=sqladmin;MultipleActiveResultSets=True"

where my initial connection string included a ";pwd=HeyYouShouldntSeeThi$"

It should work if you use Windows Authentication.

Though +1 to David's answer, use the EF's DbConnection if you need to do something tricky.

I'd also look at whether the issues can be solved with better EF querying such as leveraging projection with Select to get relevant details vs. EagerLoading, or looking for pitfalls with Lazy Loading. Personally, after working on a large number of projects with NHibernate when EF(4) was pretty useless for anything but the most trivial scenarios, to now using EF 6 pretty much exclusively, I haven't found a scenario where I've needed something like Dapper to address a scenario that at worst introduced an optimized entity model via a bounded context. And that is rare, when it is used, it's something like for supporting bulk operations. The risk of work-arounds is them becoming a crutch to hide design issues and add to the complexity of maintenance. The default approach becomes if EF seems slow, write a Dapper alternative instead of resolving what can be simple inefficiencies in how the EF code was written.

1
  • Thank you Steve! I've tried printing out the connectionstring from EF context but it have the Password property in the string. However I'm considering what you wrote about using EF6 vs Dapper, that's another aspect. Thanks again. Aug 30, 2019 at 6:22
1

Thanks for these answers, I'm adding another one: ConnectionString must include Persist Security Info=true and it works again.

However I'm preferring the solution by @David.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.