logo
Tags down

shadow

How to set up .net core service that uses a generic repository


By : Ramon Gajardo
Date : September 29 2020, 04:00 AM
will be helpful for those in need You can register the type generically, if that's what you're talking about:
code :
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));


Share : facebook icon twitter icon

Unity IoC resolving a Generic Service plus Generic repository


By : Achini Peiris
Date : March 29 2020, 07:55 AM
With these it helps experimented with UnityAutoRegistration while the latest release was still "fresh" and I was not happy with it. The TecX project on codeplex contains a port of the StructureMap config engine which gives you support for conventions that should make your life a lot easier.
Something like
code :
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.Scan(s =>
{
  s.AssembliesFromApplicationBaseDirectory();
  s.With(new ImplementsIInterfaceNameConvention());
}
var container = new UnityContainer();
container.AddExtension(builder);
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
var serviceLocator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);

Can I just use a Generic Repository and a Generic Service class for the whole project?


By : mehdi jamai
Date : March 29 2020, 07:55 AM
To fix this issue We do.
I am torn about it honestly. For smaller domains its perfectly fine and works a treat. For larger ones (like the one I am working with currently), your repository can never really be generic enough to warrant a single one.

Can not resolve a generic service using manual interception with ASP.NET Core 2 and Castle.Core


By : christiansonk
Date : March 29 2020, 07:55 AM
should help you out Here is what I had to do: Modified ConfigureService method like below:
code :
public void ConfigureServices(IServiceCollection services)
{
    IConfigurationInterceptor<T> GetConfigurationInterceptor<T>(ConfigurationInfo<T> info) where T : class 
    { 
        return new ConfigurationInterceptor<T>(info, services.GetService<IConfigurationProvider>(), Configuration);
    }

    services.AddSingletonConfiguration<IStaticDataConfiguration, StaticDataConfiguration>("someFeatureKey", GetConfigurationInterceptor);
 }
public static void AddSingletonConfiguration<TInterface, TImplementation>(this IServiceCollection services, 
    string featureName, Func<ConfigurationInfo<TImplementation>, IConfigurationInterceptor<TImplementation>> ic) where TImplementation : class, TInterface where TInterface : class
{ 
    var info = new ConfigurationInfo<TImplementation>(featureName, typeof(TInterface));
    var generator = new ProxyGenerator();
    services.AddSingleton(x =>
    {
        var icTemp = ic.Invoke(info);
        return (TInterface) generator.CreateInterfaceProxyWithoutTarget(info.ServiceType, icTemp);
    });
}
public static TInterface GetService<TInterface>(this IServiceCollection services) where TInterface : class
{ 
    var serviceProvider = services.BuildServiceProvider();
    return serviceProvider.GetRequiredService<TInterface>();
}

Using .Net Core Identity with generic repository


By : user1634415
Date : March 29 2020, 07:55 AM
wish of those help C# only supports single inheritance. You cannot inherit from two different classes. Additionally your Identity user class, must inherit from IdentityUser. You have no choice in that. As a result, the best you can do is make your user class and the rest of your entity classes implement the same interface, i.e. IEntity. Then, instead of constraining your generic type as BaseEntity, use IEntity instead.
Of course, this means you will incur a bit of code duplication as you'll have to implement IEntity separately on both BaseEntity and your user class. However, that is unavoidable.

Generic Repository pattern for .net core with Dapper


By : user1811591
Date : March 29 2020, 07:55 AM
it helps some times The examples by @PathumLakshan request from comments. Provided examples are written in asynchronous manner, but of source can be implemented synchronous. Anyway it is just an illustration of how you can manage instrastructure with Dapper. Class Db provides some generic methods for getting data and executing SQL queries. For instance you can use overload Get(string, object) for basic queries, or take Get(Func> to use let say QueryMultiple. Class Repository shows, how can look basic repository for entity Entity.
Db class:
code :
public class Db : IDb
{
    private readonly Func<SqlConnection> _dbConnectionFactory;

    public Db(Func<SqlConnection> dbConnectionFactory)
    {
        _dbConnectionFactory = dbConnectionFactory ?? throw new ArgumentNullException(nameof(dbConnectionFactory));
    }

    public async Task<T> CommandAsync<T>(Func<SqlConnection, SqlTransaction, int, Task<T>> command)
    {
        using (var connection = _dbConnectionFactory.Invoke())
        {
            await connection.OpenAsync();

            using (var transaction = connection.BeginTransaction())
            {
                try
                {
                    var result = await command(connection, transaction, Constants.CommandTimeout);

                    transaction.Commit();

                    return result;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    Logger.Instance.Error(ex);
                    throw;
                }
            }
        }
    }

    public async Task<T> GetAsync<T>(Func<SqlConnection, SqlTransaction, int, Task<T>> command)
    {
        return await CommandAsync(command);
    }

    public async Task<IList<T>> SelectAsync<T>(Func<SqlConnection, SqlTransaction, int, Task<IList<T>>> command)
    {
        return await CommandAsync(command);
    }

    public async Task ExecuteAsync(string sql, object parameters)
    {
        await CommandAsync(async (conn, trn, timeout) =>
        {
            await conn.ExecuteAsync(sql, parameters, trn, timeout);
                return 1;
        });

    public async Task<T> GetAsync<T>(string sql, object parameters)
    {
        return await CommandAsync(async (conn, trn, timeout) =>
        {
            T result = await conn.QuerySingleAsync<T>(sql, parameters, trn, timeout);
            return result;
        });
    }

    public async Task<IList<T>> SelectAsync<T>(string sql, object parameters)
    {
        return await CommandAsync<IList<T>>(async (conn, trn, timeout) =>
        {
            var result = (await conn.QueryAsync<T>(sql, parameters, trn, timeout)).ToList();
            return result;
        });
    }
}
public class Repository<Entity> : IRepository<Entity>
{
    protected readonly IDb _db;

    public Repository(IDb db)
    {
        _db = db ?? throw new
            ArgumentException(nameof(db));
    }

    public async Task Add(Entity entity)
    {
        await _db.ExecuteAsync("INSERT INTO ... VALUES...", entity);
    }

    public async Task Update(Entity entity)
    {
        await _db.ExecuteAsync("UPDATE ... SET ...", entity);
    }

    public async Task Remove(Entity entity)
    {
        await _db.ExecuteAsync("DELETE FROM ... WHERE ...", entity);
    }

    public async Task<Entity> FindByID(int id)
    {
        return await _db.GetAsync<Entity>("SELECT ... FROM ... WHERE Id = @id", new { id });
    }

    public async Task<IEnumerable<Entity>> FindAll()
    {
        return await _db.SelectAsync<Entity>("SELECT ... FROM ... ", new { });
    }
}
Related Posts Related Posts :
  • AVX2 SIMD XOR not yielding performance improvements in .NET
  • Algorithm to find the closest time
  • Xamarin Form - How To store an image in PDF or JPEG Format in UWP
  • ModelState error: The value 'null' is not valid for nullable field
  • Pre Increment of an operator
  • MSTest Asserts fail with null reference
  • Getting random numbers after a simple math problem. Might be a local variable thing
  • Convert HTML to PDF using HTML Renderer using C# and XML to Pdf
  • Conversion failed when converting varchar value to datatype bit
  • How to edit an XML file in Streamingassets from my hololens
  • Naming a DispatcherTimer based on a string from another method?
  • How to call the default browser in the Hololens app
  • How do I close an IF statement if there is no more code to be executed with 'else'?
  • Unity3D: Is there a easy way to give a min/max to a value in the inspector?
  • The type or namespace name 'ICloudRecoEventHandler' could not be found
  • When compiling C# expression trees into methods, is it possible to access "this"?
  • Sort an array of strings in ascending order in C#
  • How detect is a method in a C# class is implementing a method from an interface?
  • How to parse a timespan in order to add it to a datetime?
  • Changing code from if-statement to switch-statement in C#
  • Linq GroupBy Clause not including items with zero count
  • How to determine the highest value in a list of properties
  • C# Custom Json.NET List serialization
  • Session Variable is null after using RedirectToAction
  • How to manipulate c# code programatically In .Net Core?
  • Modifying Windows System sounds
  • Is there a way to convert this powershell script to C#
  • Lists will show null even though assigned in constructor
  • Any way to have a `using` block that doesn't define a scope block?
  • How do I get a result from this mocked service?
  • async await losing response in c#
  • How can I pause an execution without using Thread.Sleep()
  • How to Stop In Azure Ad Authentication Sign Out ask for Which account do you want to sign out of?
  • Use operators with and without space in c#
  • Remove duplicates from comma separated list
  • Use a String variable as argument from if sentence
  • unity how to avoid scaling heritage when parenting?
  • Is there a way to do nested model binding with the [FromBody] attribute?
  • How to insert dynamic query into table using c#
  • Why Unit Testing Assert.AreEqual() method does NOT pick up my own Equals() method in the customized class
  • Unity Error: Feature 'out variable declaration'
  • What happens if my C# switch expression is non-exhaustive?
  • How Can I Select an ItemTemplate Based on a Value?
  • EF Class table name and column have same name
  • Substring issues - input string was not in a correct format
  • C# Asynchronously read data from a redirected StandardOutput
  • The code after await operation is not executing
  • Image FILL logic such as "Stretch.Uniform" of WPF
  • Why am I allowed to declare a variable with the same name?
  • Simplest way to display colored 3D boxes in winforms
  • Conventions on having both an API and MVC project in .NET Core solution
  • File upload .NET Core 'IFormFile' does not contain a definition for 'CopyToAsync' and no extension method
  • Deserialize only valid objects by ignoring errors
  • How to write into text file what is ordered by years
  • Remove this 'return' statement or make it conditional
  • Cannot implicitly convert type "System.DateTime" to "LearnScan.LearnUser.NullableDateTime"
  • Why does DateTime.UtcNow.Subtract give me a massive number sometimes?
  • How to restart CancellationTokenSource after make it cancel in c#?
  • Same data is fetched from the database every time
  • JSON Deserialize is not working with List object
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk