简体   繁体   中英

Check if 'this' implements an interface then call its member from inside generic base class for subclass?

I am using Entity Framework in .NET MVC with C#. I've made an interface for POCOs whom I want to track their changes to (custom logic based on POCO, not what EF can already do). The interface:

public interface ITrackChangesService<TClass>
    {
        void SaveChanges(TClass entity);
    }

I am trying to have this be used in my EntitySevice which all POCO services inherit from, the declaration of EntityService:

 public abstract class EntityService<TRepositoryClass, TClass, TDbContext>
    where TClass : Entity, new()
    where TDbContext : DbContext, new()
    where TRepositoryClass : EntityRepository<TClass, TDbContext>, new()
{

As my comments show, I am trying to check if when Save is called from a subclass such as UserService:

public class UserService : EntityService<UserRepository, User, MyDbContext>, ITrackChangesService<User>

To see if the UserService implements ITrackChangesService and if so, call the SaveChanges method on it. This is being done in my Save method in entity service:

public virtual void Save(TClass entity)
    {
        if (entity != null)
        {
            entity.LastModifiedBy = SessionUtil.UserAbsolute == null ? "System" : SessionUtil.UserAbsolute.NetId;

            if (Exists(entity))
            {
                entity.DateModified = DateTime.Now;
                //if(this is ITrackChangesService<TClass>)
                //{
                //    (ITrackChangesService<TClass>) this.SaveChanges(entity);
                //}
                Repository.Update(entity);
            }
            else
            {
                entity.CreatedBy = SessionUtil.UserAbsolute == null ? "System" : SessionUtil.UserAbsolute.NetId;
                entity.DateCreated = DateTime.Now;
                Repository.Insert(entity);
            }
        }
    }

However I can't seem to be able to call the SaveChanges method off the calling subclass. .SaveChanges is not recognized. How do I get that to be recognized.

You're casting the return value of this.SaveChanges() instead of this .

var trackChangesService = this as ITrackChangesService<TClass>;
if(trackChangesService != null)
{
    trackChangesService.SaveChanges(entity);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM