首页 文章

设置正确的Unity容器配置以解析装饰器模式中的接口类

提问于
浏览
0

下面给出了我不同的类声明以及我如何设置统一容器配置以获得Interface to Concrete类实现 . 代码当前抛出stackoverflow异常或建议无法构造接口 .

请帮我修复类结构或容器配置 .

CodesController Class -

public class CodesController : ApiController
{
    private readonly IUnitOfWorkAsync unitOfWork;
    private readonly ICodeRepository repository;

    public CodesController(IUnitOfWorkAsync unitOfWork, ICodeRepository codeRepository)
    {
        if (unitOfWork == null)
        {
            throw new ArgumentNullException("unitOfWork");
        }

        this.unitOfWork = unitOfWork;
        this.repository = codeRepository;
    }

//Other class level methods here
}

CodeRepository class -

public class CodeRepository : ICodeRepository
{
    private readonly ICodeRepository codeRepository;

    public CodeRepository(ICodeRepository repository)
    {
        this.codeRepository = repository;
    }

    public virtual async Task<IEnumerable<Code>> GetCodeAsync(string codeKey)
    { //Some implementation here}
}

ICodeRepository Interface -

public interface ICodeRepository : IRepositoryAsync<Code>
{
    Task<IEnumerable<Code>> GetCodeAsync(string codeKey);
}

IRepositoryAsync Interface -
`public interface IRepositoryAsync<TEntity> : IRepository<TEntity> where TEntity : class, IPersistenceHint
{
Task<bool> DeleteAsync(params object[] keyValues);
Task<bool> DeleteAsync(CancellationToken cancellationToken, params object[] keyValues);
Task<TEntity> FindAsync(params object[] keyValues);
Task<TEntity> FindAsync(CancellationToken cancellationToken, params object[] keyValues);
}
Unity Container Configuration- container.RegisterType<IUnitOfWorkAsync, UnitOfWork>(
"test",
new TransientLifetimeManager(),
new InjectionConstructor(container.Resolve<IDataContextAsync>("test")));

container.RegisterType<ICodeRepository, CodeRepository>();
container.RegisterType<CodesController, CodesController>();
With this given configuration and class structure, based on my experimentation with container config, I get following exception -`

JSON
exceptionMessage=An error occurred when trying to create a controller of type 'CodesController'. Make sure that the controller has a parameterless public constructor.
exceptionType=System.InvalidOperationException
innerException
exceptionMessage=Type '<Namespace>.Api.Controllers.CodesController' does not have a default constructor
stackTrace= at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

如果这里有任何问题,请提出建议,以便我可以解决同样的问题 . 已经在这方面挣扎了很多天 .

1 回答

相关问题