PDA

View Full Version : Unable to resolve service for type while attempting to activate



sajjadzare
پنج شنبه 30 مرداد 1399, 12:44 عصر
یک پروژه NET Core MVC Web Api ایجاد کردم و از Dependency injection , Repository pattern استفاده کردم برای inject کردن repository به کنترلر ولی خطای زیر رو میگیرم

152055

نمونه کد هایی که استفاده کردم :

Startup.cs




public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();

services.AddScoped<IUnitOfWork, DatabaseContext>();
//....
}

public IServiceProvider ConfigureIoC(IServiceCollection services)
{
var container = new Container();

container.Configure(config =>
{
config.AddRegistry(new DefaultRegistry());

config.Populate(services);
});

return container.GetInstance<IServiceProvider>();
}


Class DefaultRegistry




public DefaultRegistry()
{
For<ICategoryRepository>().LifecycleIs(Lifecycles.Container).Use<CategoryRepository>();

For<IUnitOfWork>().LifecycleIs(Lifecycles.Container).Use<DatabaseContext>();
}


CategoryRepository




public interface ICategoryRepository : IGenericRepository<Category>
{
List<Category> GetAll();
Category Insert(Category model);
}

public class CategoryRepository : GenericRepository<Category>, ICategoryRepository
{
IUnitOfWork _uow;
Lazy<DbSet<Category>> _categories;
public CategoryRepository(IUnitOfWork uow) : base(uow)
{
_uow = uow;
_categories = new Lazy<DbSet<Category>>(() => _uow.Set<Category>());
}

//....
}






BaseApiController




public class BaseApiController : Controller
{
public IUnitOfWork _uow { get; set; }

public BaseApiController(IUnitOfWork uow)
{
_uow = uow;
}
}


CategoryController




public class CategoryController : BaseApiController
{
Lazy<ICategoryRepository> _categoryRepository;

public CategoryController(IUnitOfWork uow, Lazy<ICategoryRepository> CategoryRepository) : base(uow)
{
_categoryRepository = CategoryRepository;
}

[HttpGet, Route("getall")]
public ActionResult GetGategories()
{
List<Category> lst = _categoryRepository.Value.GetAll();

GetCategoriesResponse Response = new GetCategoriesResponse();
Response.Categories = lst;
Response.Result = ResponseEnum.OK;
return Ok(Response);
}
}

مهدی کرامتی
یک شنبه 02 شهریور 1399, 18:29 عصر
لطفا جهت بررسی بهتر، یک پروژه نمونه بسازید و بصورت ضمیمه یا ... در دسترس قرار دهید. با مرور کدهایی که گذاشته اید چیز خاصی به نظر نمیاد.