body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have seen a lot of Repository pattern implementations with Unit of Work. The simplest way of implementing this I came across is using hard-coded repos (such as <a href="https://www.c-sharpcorner.com/UploadFile/b1df45/unit-of-work-in-repository-pattern/" rel="nofollow noreferrer">this one</a>), while <a href="https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="nofollow noreferrer">the way recommended by Microsoft</a> improves on this with a generic repo interface, but the repos themselves are still stored in the instance.</p> <p>It is possible to improve on this by combining UoW with using a generated data access layer that uses a base repository implementation, something similar to what they implemented <a href="https://dotnettutorials.net/lesson/generic-repository-pattern-csharp-mvc/" rel="nofollow noreferrer">here</a>). A problem with this approach is if you want to implement it inside the UoW, you will have to hard-code the base class implementation. In the examples, I use EFCore, but my question is not fixed on that.</p> <p>So here is my BaseRepo, where <code>IDbEntry</code> is just a simple interface requiring an Id:</p> <pre><code>public class RepoBase&lt;TContext, TEntry&gt; : IRepository&lt;TEntry&gt; where TContext:DbContext where TEntry:class, IDbEntry { private TContext context; public RepoBase(TContext context) { this.context = context; } // skipping generic CRUD method implementations... } </code></pre> <p>Here I used a UoW interface that can generate the generic repo on demand:</p> <pre><code>public interface IUnitOfWork { Task SaveChangesAsync(CancellationToken token = default); IRepository&lt;TEntity&gt; GetRepo&lt;TEntity&gt;() where TEntity : class, IDbEntry; } </code></pre> <p>Here is the implementation, note that the base repo also implements <code>IRepository&lt;TEntry&gt;</code>:</p> <pre><code>public class UnitOfWork&lt;TContext&gt; : IUnitOfWork where TContext : DbContext { private readonly TContext context; public UnitOfWork(TContext context) { this.context = context; } public async Task SaveChangesAsync(CancellationToken token = default) { // skipping lot of additional stuff here like audit... await this.context.SaveChangesAsync(token) .ConfigureAwait(false); } IRepository&lt;TEntity&gt; IUnitOfWork.GetRepo&lt;TEntity&gt;() { return new BaseRepo&lt;TContext, TEntity&gt;(this.context); } } </code></pre> <p>This is not efficient enough, because in case of any change to the base implementation, you have to modify the UoW and you can not unit test the UoW implementation either, since it will use a real base repo implementation. So, I was wondering if I can make this work using an injected base repository implementation. Here are my modifications:</p> <p>First I added an interface for the base repo that extends the original IRepo with the ability to register a DataContext for the UoW after instantiation:</p> <pre><code>public interface IRepoBase&lt;TContext, TEntry&gt; : IRepository&lt;TEntry&gt; where TContext : DbContext where TEntry : class, IDbEntry { void RegisterSharedContext(TContext context); } </code></pre> <p>Since I wanted to use this with the built-in .net core DI, I registered it:</p> <pre><code>services.AddScoped(typeof(IRepoBase&lt;,&gt;), typeof(RepoBase&lt;,&gt;)); </code></pre> <p>Since I do not know which type will the UoW required to locate, I can only resolve the base repo inside the generic method call. To do this, I need to inject a <code>IServiceProvider</code> instance into my UoW:</p> <pre><code> public UnitOfWork(TContext context, IServiceProvider services) { this.context = context; this.services = services; } </code></pre> <p>and use it to resolve the base repo:</p> <pre><code>IRepository&lt;TEntity&gt; IRepoManager.GetRepo&lt;TEntity&gt;() { var baseRepo = services.GetRequiredService&lt;IRepoBase&lt;TContext, TEntity&gt;&gt;(); baseRepo.RegisterSharedContext(this.context); return baseRepo; } </code></pre> <p>This is better because now I only need to change the DI registration to change the base repo implementation and theoretically I can unit test the UoW as well. But, to do that, I have to mock an <code>IServiceProvider</code> (which is a practice I have never encountered) not to mention that mixing DI and service locator is highly discouraged in the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2" rel="nofollow noreferrer">Microsoft DI guidelines</a>. I'm also not a fan of registering a context after instantiation as this is another necessary step that other developers simply have to remember for this to work.</p> <p>I'm interested in the opinion of more experienced .Net developers: how can I approach this problem or is this something I should be concerned with in the first place?</p> <p>As a side note, I know that EFCore implements UoW and implementing one yourself is only advised in <a href="https://softwareengineering.stackexchange.com/questions/406729/is-unit-of-work-pattern-really-needed-with-repository-pattern">somewhat special</a> situations.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:08:59.237", "Id": "270684", "Score": "0", "Tags": [ "c#", "generics", "dependency-injection", "asp.net-core", "repository" ], "Title": "Generic Base Repository implementation with Unit of Work in C#" }
270684
<p>In my app users can create and soft-delete gateways.<br /> I've written the logic in a transaction also locking a matching record (on <code>website</code> field) which was soft-deleted by the user because of race-condition. Read code for a better understanding.</p> <p><strong>Already exists (soft-deleted)</strong><br /> These gateways must be verified by admin, if the user submits different <code>website</code> and <code>description</code> fields in comparison to the matching record which was already verified, set <code>is_verified</code> and <code>rejection_reason</code> to <code>null</code></p> <p><strong><code>is_verified</code> values:</strong></p> <ul> <li><code>true</code> verified</li> <li><code>false</code> rejected</li> <li><code>null</code> pending</li> </ul> <p><strong>The Rule:</strong> Create if not exists, Restore if soft-deleted.</p> <p>Somehow i think my code is not ok and i'm overthinking or anything else (as a perfectionist + imposter syndrome).</p> <p><strong>Migration</strong></p> <pre><code>Schema::create('gateways', function (Blueprint $table) { $table-&gt;id(); $table-&gt;foreignId('user_id') -&gt;constrained() -&gt;onUpdate('cascade') -&gt;onDelete('cascade'); $table-&gt;string('title', 50); $table-&gt;text('description'); $table-&gt;string('website')-&gt;unique(); $table-&gt;enum('wage', Gateway::getWageKeys()); $table-&gt;text('rejection_reason')-&gt;nullable(); $table-&gt;boolean('is_verified')-&gt;nullable()-&gt;default(null); $table-&gt;boolean('is_blocked')-&gt;default(false); $table-&gt;boolean('first_payment')-&gt;default(false); $table-&gt;dateTime('free_until')-&gt;nullable(); $table-&gt;softDeletes(); $table-&gt;timestamps(); }); </code></pre> <p><strong>Controller</strong></p> <pre class="lang-php prettyprint-override"><code>/** * Create a new gateway. * * @param \App\Http\Requests\StoreGatewayRequest $request * @return \App\Http\Resources\GatewayResource */ public function create(StoreGatewayRequest $request) { try { $gateway = DB::transaction(function () use ($request) { $gateway = $request-&gt;user()-&gt;gateways()-&gt;onlyTrashed() -&gt;where('website', $request-&gt;website)-&gt;lockForUpdate()-&gt;first(); if (! $gateway) { return $request-&gt;user()-&gt;gateways()-&gt;create($request-&gt;validated()); } else { if ($gateway-&gt;is_blocked) abort(452); $gateway-&gt;fill($request-&gt;validated()); if ($gateway-&gt;isDirty('website') || $gateway-&gt;isDirty('description')) { $gateway-&gt;rejection_reason = null; $gateway-&gt;is_verified = null; } $gateway-&gt;deleted_at = null; $gateway-&gt;save(); return $gateway; } }); } catch (QueryException $e) { if ($e-&gt;errorInfo[1] === 1062) { abort(409); } else { throw $e; } } return new GatewayResource($gateway); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-05T00:50:57.323", "Id": "270691", "Score": "0", "Tags": [ "php", "laravel", "eloquent" ], "Title": "Overthinking a create or restore logic in laravel" }
270691
<p><strong>Context:</strong> My question (duplicated from <a href="https://stackoverflow.com/posts/70230005/">this question on SO</a> comes from needing to iterate different variables from <code>np.arange</code> arrays. The idea is to generate something like a &quot;vector matrix&quot; containing an element of each parameter &quot;vector&quot;. For the sake of simplicity, if a,b,..., are a fixed number of (8) <code>np.ndarray</code>s; and x, y, z are a fixed number (3) of quantities that be floats or arrays (or any combination of), I expect something like</p> <pre><code>a = np.array([a0,a1,a2]) b = np.array([b0,b1,b2]) ... h = np.array([h0,h1,h2]) x = x0 z = np.array([z0,z1,z2]) y = y0 def Generate(a,b,c,d,e,f,g,h,x,z,y): ... return returned_array print(Generate(a,b,c,d,e,f,g,h,x,y,z)) &gt;&gt; ([[a0,b0,c0,d0,e0,f0,g0,x0,z0,y0] [a1,b1,c1,d1,e1,f1,g1,x0,z1,y0] [a2,b2,c2,d2,e2,f2,g2,x0,z2,y0] ... ]) </code></pre> <p>But accounting for every combination possible (in this case, 3^7 to 3^10). See that</p> <p><code>returned_array=np.array([[a0,b0,...,x0*,y0*,z0*],[a1,b1,...,x1*,y1*,z1*],...,[aN,bN,...,xN*,yN*,zN*]])</code></p> <p>could also be (if x = x is float instead of x = np.arange(...)):</p> <p><code>[[a0,b0,...,x,y0*,z0*],[a1,b1,...,x,y1*,z1*],...,[aN,bN,...,x,yN*,zN*]]</code></p> <p>or (if x = x and z=z are floats instead of x,z = np.arange(...),np.arange(...)):</p> <p><code>[[a0,b0,...,x,y0*,z],[a1,b1,...,x,y1*,z],...,[aN,bN,...,x,yN*,z]]</code></p> <p>or any other combination of x,y,z being arrays or floats. I'm actually trying with something like:</p> <pre><code>a=np.arange(a0,af,N) ll=[] for aparam in a: for bparam in b: for ... : if isinstance(x, np.ndarray) == True: for xparam in x: l.append([aparam,bparam,...,xparam]) else: #x is float l.append([aparams,bparams,...,x]) -&gt;|| if isinstance(y, np.ndarray) == True: -&gt;|| if isinstance(z, np.ndarray) == True: ... </code></pre> <p>for <code> -&gt;||</code> I meant to say that those conditional expressions are somewhere inside for loops. As I know <code>x,y,z</code> are only 3 (quantities that could be np.ndarray or floats) I guess I can cover each case.</p> <p><strong>You can check the code here</strong>:</p> <pre><code>import random import numpy as np import numbers a = np.random.uniform(1,10,2) b = np.random.uniform(1,10,2) c = np.random.uniform(1,10,2) w=[36] x = np.random.normal(2,1e-1,2) #This could be a float y = np.random.normal(3,1e-1,2) #This could be a float z = np.random.normal(4,1e-1,2) #This could be a float #Different combinations: options=[['N',1],['L',2]] for i in options: for j in options: for k in options: print(i[0]+j[0]+k[0]+' w/ total combinations: '+str(2*2*2*i[1]*j[1]*k[1])) #Now interate def iter_func(args): returned_array = [] a,b,c,x,y,z = args for avals in a: for bvals in b: for cvals in c: if isinstance(x,np.ndarray)==True: for xvals in x: if isinstance(y,np.ndarray)==True: for yvals in y: if isinstance(z,np.ndarray)==True: for zvals in z: returned_array.append([avals,bvals,cvals,xvals,yvals,zvals]) elif isinstance(z,numbers.Real)==True or isinstance(z,list)==True and len(z)==1: returned_array.append([avals,bvals,cvals,xvals,yvals,z]) elif isinstance(y,numbers.Real)==True or isinstance(y,list)==True and len(y)==1: returned_array.append([avals,bvals,cvals,xvals,y,z]) elif isinstance(x,numbers.Real)==True or isinstance(x,list)==True and len(x)==1: if isinstance(y,np.ndarray)==True: for yvals in y: if isinstance(z,np.ndarray)==True: for zvals in z: returned_array.append([avals,bvals,cvals,x,yvals,zvals]) elif isinstance(z,numbers.Real)==True or isinstance(z,list)==True and len(z)==1: returned_array.append([avals,bvals,cvals,x,yvals,z]) elif isinstance(y,numbers.Real)==True or isinstance(y,list)==True and len(y)==1: if isinstance(z,np.ndarray)==True: for zvals in z: returned_array.append([avals,bvals,cvals,x,y,zvals]) elif isinstance(z,numbers.Real)==True or isinstance(z,list)==True and len(z)==1: returned_array.append([avals,bvals,cvals,x,y,z]) return returned_array #Case test: last 3 are lists of numbers returned_array = iter_func([a,b,c,w,w,w]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 1: NNN returned_array = iter_func([a,b,c,w[0],w[0],w[0]]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 2: NNL returned_array = iter_func([a,b,c,w[0],w[0],z]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 3: NLN returned_array = iter_func([a,b,c,w[0],y,w[0]]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 4: NLL returned_array = iter_func([a,b,c,w[0],y,z]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 5: LNN returned_array = iter_func([a,b,c,x,w[0],w[0]]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 6: LNL returned_array = iter_func([a,b,c,x,w[0],z]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 7: LLN returned_array = iter_func([a,b,c,x,y,w[0]]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') #Case 8: LLL returned_array = iter_func([a,b,c,x,y,z]) print('total combinations: '+str(len(returned_array))) for i in returned_array: print(i) print('\n') </code></pre> <p>with output:</p> <pre><code>total combinations: 8 [2.8336495994988162, 5.295916749347686, 4.929950792386235, [36], [36], [36]] [2.8336495994988162, 5.295916749347686, 9.493663046965622, [36], [36], [36]] [2.8336495994988162, 9.869611330430935, 4.929950792386235, [36], [36], [36]] [2.8336495994988162, 9.869611330430935, 9.493663046965622, [36], [36], [36]] [2.741768057298594, 5.295916749347686, 4.929950792386235, [36], [36], [36]] [2.741768057298594, 5.295916749347686, 9.493663046965622, [36], [36], [36]] [2.741768057298594, 9.869611330430935, 4.929950792386235, [36], [36], [36]] [2.741768057298594, 9.869611330430935, 9.493663046965622, [36], [36], [36]] total combinations: 8 [2.8336495994988162, 5.295916749347686, 4.929950792386235, 36, 36, 36] [2.8336495994988162, 5.295916749347686, 9.493663046965622, 36, 36, 36] [2.8336495994988162, 9.869611330430935, 4.929950792386235, 36, 36, 36] [2.8336495994988162, 9.869611330430935, 9.493663046965622, 36, 36, 36] [2.741768057298594, 5.295916749347686, 4.929950792386235, 36, 36, 36] [2.741768057298594, 5.295916749347686, 9.493663046965622, 36, 36, 36] [2.741768057298594, 9.869611330430935, 4.929950792386235, 36, 36, 36] [2.741768057298594, 9.869611330430935, 9.493663046965622, 36, 36, 36] total combinations: 16 [2.8336495994988162, 5.295916749347686, 4.929950792386235, 36, 36, 3.8501788450044114] [2.8336495994988162, 5.295916749347686, 4.929950792386235, 36, 36, 3.895647492990764] [2.8336495994988162, 5.295916749347686, 9.493663046965622, 36, 36, 3.8501788450044114] [2.8336495994988162, 5.295916749347686, 9.493663046965622, 36, 36, 3.895647492990764] [2.8336495994988162, 9.869611330430935, 4.929950792386235, 36, 36, 3.8501788450044114] [2.8336495994988162, 9.869611330430935, 4.929950792386235, 36, 36, 3.895647492990764] [2.8336495994988162, 9.869611330430935, 9.493663046965622, 36, 36, 3.8501788450044114] [2.8336495994988162, 9.869611330430935, 9.493663046965622, 36, 36, 3.895647492990764] [2.741768057298594, 5.295916749347686, 4.929950792386235, 36, 36, 3.8501788450044114] [2.741768057298594, 5.295916749347686, 4.929950792386235, 36, 36, 3.895647492990764] [2.741768057298594, 5.295916749347686, 9.493663046965622, 36, 36, 3.8501788450044114] [2.741768057298594, 5.295916749347686, 9.493663046965622, 36, 36, 3.895647492990764] [2.741768057298594, 9.869611330430935, 4.929950792386235, 36, 36, 3.8501788450044114] [2.741768057298594, 9.869611330430935, 4.929950792386235, 36, 36, 3.895647492990764] [2.741768057298594, 9.869611330430935, 9.493663046965622, 36, 36, 3.8501788450044114] [2.741768057298594, 9.869611330430935, 9.493663046965622, 36, 36, 3.895647492990764] </code></pre> <p><strong>Q:</strong> is this called &quot;variable-depth for-loops&quot;, &quot;nested for-loops&quot;? Any comment on this would be highly appreciated.</p> <p>I'm not very familiar with Python but <strong>Q:</strong> I think it could be done in a simplier way. What would you suggest? Any hint? Maybe a way to do it with pandas, numpy or in a big list comprehension? (I do not really know if possible). I apologize if the question is vague. I'd be happy if you suggest <em>anything to make the question clearer</em>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-05T01:45:41.820", "Id": "270692", "Score": "0", "Tags": [ "python", "python-3.x", "iteration", "nested" ], "Title": "Python - nested loop; Iterate through parameters elements with condition" }
270692