Witam.
W moich walkach z wdrażaniem wzorca MPV przyszedł czas na Dependenc Injection. No i natrafiłem na taki oto problem:
using Autofac;
using System.Linq;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Model;
using Model.Entities;
namespace DataTest
{
public class DIResolver
{
public static T Resolve<T>()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<DbContextMySql>().As<IDbContext>()
.WithParameter(new NamedParameter("name", "sopdContext"))
;
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<T>();
return service;
}
}
}
[TestClass]
public class ContextTest
{
[TestMethod]
public void GetContext()
{
IDbContext AppContext = DIResolver.Resolve<IDbContext>();
var users = AppContext.Users.Select(u => new UserEntity()).ToList();
foreach(var item in users)
Trace.TraceInformation("User name :{0}", item.SurName);
}
}
}
Test rzuca wyjątkiem:
Test Name: GetContext
Test FullName: DataTest.ContextTest.GetContext
Test Source: d:\dev\C#\Workspace_sopd\DataTest\ContextTest.cs : line 35
Test Outcome: Failed
Test Duration: 000,2624654
Result Message:
Test method DataTest.ContextTest.GetContext threw exception:
System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
Result StackTrace:
w System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
w System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
w System.Data.Entity.Internal.Linq.InternalSet1.Initialize() w System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext()
w System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() w System.Linq.Queryable.Select[TSource,TResult](IQueryable
1 source, Expression`1 selector)
w DataTest.ContextTest.GetContext() w d:\dev\C#\Workspace_sopd\DataTest\ContextTest.cs:wiersz 37
Przypuszczam że problem siedzi w konfiguracji wpisu w kontenerze ale niestety googlowe podpowiedzi nic nie dają.
Pomoże ktoś?