1

I understand the concept of how to create generic class in C# quit well but what I'm trying to archive is a little bit different from what I've done before.

I use to create Service Management classes and write and all the methods I'll be needing in the controller layer using dependency Injections but i figured that am doing the same thing over and over for all my entities so I wanted to leverage the concept of Generic class which am already using as my Repository in the service layer as well so I'll cut the pain of rewriting the same thing over and over.

So this is what I've done so far, I went ahead and create the a concrete Generic Class

/// <summary>
/// Base Service Generic Class
/// </summary>
/// <typeparam name="TEntity"> Domain Entity</typeparam>
/// <typeparam name="TDataObject"> Data Object</typeparam>
public class BaseServices<TEntity, TDataObject> where TEntity : class, IDataObject, new()
{
    public FMDbContext _context;

    public IFactoryInit _factory;
    public IUnitOfWork _uow;

    public BaseServices(IUnitOfWork uow, IFactoryInit factory)
    {
        _uow = uow;
        _factory = factory;
    }

    private Repository<TEntity> _repository { get; }
    private ServiceFactory _serviceFactory { get; }


    public Repository<TEntity> Repository
    {
        get { return _repository ?? new Repository<TEntity>(_context); }
    }

    public ServiceFactory SFactory
    {
        get { return _serviceFactory ?? new ServiceFactory(); }
    }


    public class ServiceFactory : BaseFactory<TEntity, TDataObject>
    {
    }

    public TDataObject GetSingle(Guid id)
    {
        try
        {
            TEntity _entity = Repository.GetById(id);
            var _obj = SFactory.SingleMappingEntityToObject(_entity);

            return _obj;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public IEnumerable<TDataObject> GetMany()
    {
        try
        {
            var entities = Repository.Get(null, null, false);
            var _objs = SFactory.ListMappingEntitiesToObjects(entities);

            return _objs;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public Task<TDataObject> CreateAsync(TDataObject obj)
    {
        return Task.Run(() =>
        {
            try
            {
                var entity = SFactory.SingleMappingObjectToEntity(obj);
                entity.Id = IdentityGenerator.NewSequentialGuid();
                Repository.Insert(entity: entity);
                _context.SaveChangesAsync();
                var _resp = SFactory.SingleMappingEntityToObject(entity);
                return _resp;

                throw new InvalidOperationException("Internal Server Error!");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        });
    }}

As you've seen I brought in my IUnitOfWork where am initialising all my repository inside.

And now this is how am calling it on my service

 public class ProductService : BaseServices<Product, ProductObject>
{

    public ProductService(IUnitOfWork uow, IFactoryInit factory) : base(uow, factory)
    {
    }
}

Then I went ahead to bring all the servies in one class so I can use .Net Core Dependency Injection to bind it once

 public class ServiceInit : IServiceInit
{
    private IFactoryInit _factory;
    private IUnitOfWork _uow;

    private ProductService _productService;

    public ProductService ProductServices
    {
        get { return _productService ?? new ProductService(_uow, _factory); }
    }
}

That's all I've done but I keep getting Null Reference Exception in my UnitOfWork initialisation and I even tried this

public IUnitOfWork UnitOfWork
    {
        get
        {
            if (_uow == null)
            {
                _uow = new UnitOfWork(_context);
            }
            return _uow;
        }
    }

Explicitly and am still get null reference

But this pattern is still working perfectly well, which is the pattern of creating services repeatedly for all my entity which am very tired of

{
public class VendorManagementServices : IVendorManagementServices
{
    private IFactoryInit _factory;
    private IUnitOfWork _uow;

    public VendorManagementServices(IUnitOfWork uow, IFactoryInit factory)
    {
        _uow = uow;
        _factory = factory;
    }
}

So, I dont know what am missing in my BaseService that keeps throwing

System.NullReferenceException: Object reference not set to an instance of an object.

Any Ideas guys?

Andy Mike
  • 65
  • 1
  • 2
  • 12
  • 1
    Never do `throw ex;` If you're not going to handle it, don't bother catching it. If you are going to catch it and then do something and later want to throw it again, just put `throw;`. As for your error, you need to identify what's null. That should be simple once you understand what a NullReferenceException is. – mason May 28 '17 at 19:25
  • Thanks mason, but am still gonna bring it my logging plugin, for now just wanted to see what's happening and I've debugged and still getting nowhere. – Andy Mike May 28 '17 at 19:33
  • Specifically what is null? What line throws the exception? – mason May 28 '17 at 19:34
  • The UnitOfWork throws null reference for all the Repos in it. `IUnitOfWork _uow;` – Andy Mike May 28 '17 at 19:41
  • That doesn't answer my question. Please read it again. – mason May 28 '17 at 19:41
  • This `var entities = Repository.Get(null, null, false);` and this as well `var entities = _uow.ProductRepository.Get(null, null, false);` from the product service – Andy Mike May 28 '17 at 19:54
  • So now determine what's null. Is _uow null? Or ProductRepository? – mason May 28 '17 at 19:56
  • _uow is null. When I debug, I check the initialisation and I'm seeing null – Andy Mike May 28 '17 at 20:02
  • Okay so backtrack to where you initialize it and make sure it initializes it. – mason May 28 '17 at 20:03
  • Same thing, just tried this again `if (_uow == null) { _uow = new UnitOfWork(_context); }` when it comes back I check the _uow and Repos in it are null couldn't bring them along, Still can't figue what I left out. – Andy Mike May 28 '17 at 20:19
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mason May 28 '17 at 20:25
  • Thanks mason I've tracked it, It actually my context that I didn't initialize in here `ServiceInit` at the constructor level It fine now thank you. – Andy Mike May 28 '17 at 20:38

0 Answers0