Autofac和WebApi

时间:2015-07-04 10:07:04

标签: c# asp.net-web-api autofac

我在项目中使用Autofac for IoC。我有存储库,服务和web api的层。

我的web api项目中有一个AutofacWebApi类,用于注册存储库,服务和dbcontext。

public class AutofacWebApi
{
    public static void Initialize(HttpConfiguration config)
    {
        Initialize(config, RegisterServices(new ContainerBuilder()));
    }

    public static void Initialize(HttpConfiguration config, IContainer container)
    {
        config.DependencyResolver =
        new AutofacWebApiDependencyResolver(container);
    }

    private static IContainer RegisterServices(ContainerBuilder builder)
    {
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        // registration goes here


        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();

        //EF DbContext
        builder.RegisterType(typeof(MOCContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
        builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerLifetimeScope();
        //Repositories
        builder.RegisterGeneric(typeof(GenericRepository<>)).As(typeof(IGenericRepository<>)).InstancePerLifetimeScope();

        builder.RegisterType<CityRepository>()
            .As<ICityRepository>()
            .InstancePerLifetimeScope();

        //Services
        builder.RegisterType<CityService>().As<ICityService>().InstancePerLifetimeScope();

        return builder.Build();
    }
}

我的网络api控制器就像这样

public class CityController : ApiController
{
    readonly ICityService _cityService;

    public CityController(ICityService cityService)
    {
        _cityService = cityService;
    }

    public IHttpActionResult Get(int id)
    {
        var result = _cityService.GetById(id);
        return Ok("fdsafds");
    }
}

当我调用方法GetById时,我得到null,但我知道该方法应该返回一些东西,因为如果我从mvc应用程序调用相同的方法,我得到了正确的结果。 CityService

public class CityService : ICityService
{
    IUnitOfWork _unitOfWork;
    ICityRepository _cityRepository;

    public CityService(IUnitOfWork unitOfWork, ICityRepository cityRepository)
        : base()
    {
        _unitOfWork = unitOfWork;
        _cityRepository = cityRepository;
    }


    public CityDTO GetById(int Id)
    {
        var result=_cityRepository.GetById(Id);

        Mapper.CreateMap<City, CityDTO>()
            .ForMember(x=>x.Id,m=>m.MapFrom(d=>d.Id));

        var map = Mapper.Map<City, CityDTO>(result);

        return map;
    }
}

ICityService

public interface ICityService
{
    CityDTO GetById(int Id);
}

ICityRepository

public interface ICityRepository:IGenericRepository<City>
{
    City GetById(int id);
}

CityRepository

public class CityRepository:GenericRepository<City>, ICityRepository
{
    public CityRepository(DbContext context)
        : base(context)
    {

    }

    public City GetById(int id)
    {
        var result = Get(x => x.Id == id);
        return result;
    }
}

IGenericRepository

public interface IGenericRepository<T> where T : BaseEntity
{

    IEnumerable<T> GetAll();
    IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate);
    T Add(T entity);
    T Delete(T entity);
    void Edit(T entity);
    void Save();
}

GenericRepository

public abstract class GenericRepository<T> : IGenericRepository<T>
   where T : BaseEntity
{
    protected DbContext _entities;
    protected readonly IDbSet<T> _dbset;

    public GenericRepository(DbContext context)
    {
        _entities = context;
        _dbset = context.Set<T>();
    }

    public virtual IEnumerable<T> GetAll()
    {

        return _dbset.AsEnumerable<T>();
    }

    public T Get(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {

        T query = _dbset.Where(predicate).SingleOrDefault();
        return query;
    }

    public IEnumerable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {

        IEnumerable<T> query = _dbset.Where(predicate).AsEnumerable();
        return query;
    }



    public virtual T Add(T entity)
    {
        return _dbset.Add(entity);
    }

    public virtual T Delete(T entity)
    {
        return _dbset.Remove(entity);
    }

    public virtual void Edit(T entity)
    {
        _entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
    }

    public virtual void Save()
    {
        _entities.SaveChanges();
    }
}

我不知道为什么方法GetById返回结果null。 感谢

0 个答案:

没有答案