Я пытаюсь использовать единство автоматически впрыскивать DataContext в моем хранилище, используя новый экземпляр каждый раз .., моя идея является обеспечить, чтобы каждый раз, когда новый DataContext впрыскиваетсяUNITY: каждый раз переходя в новый datacontext?
В настоящее время его неудача в создании хранилища, я думаю, что он не может разрешить MyDataContext
Перед созданием конструктора на «хранилище» (см ниже), чтобы взять в DataContext на моем хранилище все работало, но теперь его провал ..
в настоящее время я эту установку в моем контейнере единства, который я создаю в global.asax, я также зарегистрировал тип MyDataContext, который является стандартным DataContext
container = new UnityContainer();
Container.RegisterType<MyDataContext, MyDataContext>()
.RegisterType<IOfficeRepository, OfficeRepository>()
.RegisterType<IOfficeService, OfficeService>();
в основном у меня есть сервис, который вызывает хранилище, как так
public class OfficeService : IOfficeService
{
IOfficeRepository repository = null;
public OfficeService(IOfficeRepository repository)
{
this.repository = repository;
if (this.repository == null)
throw new InvalidOperationException("Repository cannot be null");
}
здесь мой репозиторий
public class OfficeRepository : IOfficeRepository
{
private MyDataContext db;
public OfficeRepository (MyDataContext dataContext)
{
this.db = dataContext;
}
EDIT
Я почти забыл, что я делаю это для создания сервиса
officeService = Bootstrapper.Container.Resolve<IOfficeService>();
EDIT - ОШИБКА СРЕДСТВО СГЕНЕРИРОВАННЫМИ
Resolution of the dependency failed, type = "MarkSmith.IOfficeService", name = "".
Exception message is: The current build operation (build key Build
Key[MarkSmith.OfficeService, null]) failed: The parameter repository could not be
resolved when attempting to call constructor
MarkSmith.OfficeService(MarkSmith.IOfficeRepository repository). (Strategy type BuildPlanStrategy, index 3)
EDIT - УДАЛЕНИЕ Конструктор на хранилище работает
Это что-то делать с DataContext, потому что если я удалить constrcutor на репозиторий, который принимает DataContext, тогда все работает, но, конечно, мне нужно, чтобы он принял DataContext, чтобы каждый раз вводить «NEW» datacontext
public class OfficeRepository : IOfficeRepository
{
private MyDataContext db new MyDataContext(); // CHANGE
//public OfficeRepository (MyDataContext dataContext)
//{
//this.db = dataContext;
//}
EDIT - АКТУАЛЬНО ОШИБКА
После копать глубже я нашел эту ошибку ....
The type MyDataContext has multiple constructors of length 2.
Unable to disambiguate. (Strategy type DynamicMethodConstructorStrategy, index 0)
(Strategy type BuildPlanStrategy, index 3)
EDIT - TEST РАЗРЕШИТЬ DataContext с 1 строки кода
Это также не работает с той же ошибкой, что и выше, - несколько конструкторов
MyDataContext test = Bootstrapper.Container.Resolve<MyDataContext >();
EDIT - ВСЕ CONSTRUCTORS НА МОЕ DataContext
Они были создаваемом exernal Util, но все должно быть хорошо ..
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext()
: base(ConnectionString, mappingCache)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(string connection)
: base(connection, mappingCache)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(System.Data.IDbConnection connection)
: base(connection, mappingCache)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource)
: base(connection, mappingSource)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource)
: base(connection, mappingSource)
{
OnCreated();
}
EDIT - Для того, чтобы продемонстрировать создание DataContext в коде без единства работает 100% без проблем
MyDataContext tes2t = new MyDataContext();
Обновленный вопрос, чтобы показать, как я разрешаю свое обслуживание, используя единство –
Что произойдет, если вы попытаетесь разрешить экземпляр MyDataContext, используя в разных точках? Все, кажется, в порядке, но это может дать нам ключ. – GraemeF
Кроме того, есть ли недостающая строка или опечатка в первом извлечении кода? Похоже, что 'container' и' Container' будут разными экземплярами. Вы можете проверить, что у вас есть экземпляр, который вы ожидаете, используя отладчик. – GraemeF